I am trying to open a sample project in the farseer with monogame in vs2017 but all the time I get this error:
internal static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
///
private static void Main(string[] args)
{
using (FarseerPhysicsGame game = new FarseerPhysicsGame())
{
game.Run();
}
}
}
Related
Hey i'm new to literally everything, sorry if this was solved but i'm having trouble editing a script from Unity's Platformer 2D Game. There's an Error where Player can't die and the error NullReferenceException: Object reference not set to an instance of an object. But idk the solution.
NullReferenceException: Object reference not set to an instance of an object
Platformer.Gameplay.PlayerDeath.Execute () (at Assets/Scripts/Gameplay/PlayerDeath.cs:20)
Platformer.Core.Simulation+Event`1[T].ExecuteEvent () (at Assets/Scripts/Core/Simulation.Event.cs:57)
Platformer.Core.Simulation.Tick () (at Assets/Scripts/Core/Simulation.cs:114)
Platformer.Mechanics.GameController.Update () (at Assets/Scripts/Mechanics/GameController.cs:40)
This is my PlayerDeath
using System.Collections;
using System.Collections.Generic;
using Platformer.Core;
using Platformer.Model;
using UnityEngine;
namespace Platformer.Gameplay
{
/// <summary>
/// Fired when the player has died.
/// </summary>
/// <typeparam name="PlayerDeath"></typeparam>
public class PlayerDeath : Simulation.Event<PlayerDeath>
{
PlatformerModel model = Simulation.GetModel<PlatformerModel>();
public override void Execute()
{
var player = model.player;
if (player.health.IsAlive)
{
player.health.Die();
model.virtualCamera.m_Follow = null;
model.virtualCamera.m_LookAt = null;
// player.collider.enabled = false;
player.controlEnabled = false;
if (player.audioSource && player.ouchAudio)
player.audioSource.PlayOneShot(player.ouchAudio);
player.animator.SetTrigger("hurt");
player.animator.SetBool("dead", true);
Simulation.Schedule<PlayerSpawn>(2);
}
}
}
}
This is my Simulation.Event
using System.Collections.Generic;
namespace Platformer.Core
{
public static partial class Simulation
{
/// <summary>
/// An event is something that happens at a point in time in a simulation.
/// The Precondition method is used to check if the event should be executed,
/// as conditions may have changed in the simulation since the event was
/// originally scheduled.
/// </summary>
/// <typeparam name="Event"></typeparam>
public abstract class Event : System.IComparable<Event>
{
internal float tick;
public int CompareTo(Event other)
{
return tick.CompareTo(other.tick);
}
public abstract void Execute();
public virtual bool Precondition() => true;
internal virtual void ExecuteEvent()
{
if (Precondition())
Execute();
}
/// <summary>
/// This method is generally used to set references to null when required.
/// It is automatically called by the Simulation when an event has completed.
/// </summary>
internal virtual void Cleanup()
{
}
}
/// <summary>
/// Event<T> adds the ability to hook into the OnExecute callback
/// whenever the event is executed. Use this class to allow functionality
/// to be plugged into your application with minimal or zero configuration.
/// </summary>
/// <typeparam name="T"></typeparam>
public abstract class Event<T> : Event where T : Event<T>
{
public static System.Action<T> OnExecute;
internal override void ExecuteEvent()
{
if (Precondition())
{
Execute();
OnExecute?.Invoke((T)this);
}
}
}
}
}
This is my Simulation
using System;
using System.Collections.Generic;
using UnityEngine;
namespace Platformer.Core
{
/// <summary>
/// The Simulation class implements the discrete event simulator pattern.
/// Events are pooled, with a default capacity of 4 instances.
/// </summary>
public static partial class Simulation
{
static HeapQueue<Event> eventQueue = new HeapQueue<Event>();
static Dictionary<System.Type, Stack<Event>> eventPools = new Dictionary<System.Type, Stack<Event>>();
/// <summary>
/// Create a new event of type T and return it, but do not schedule it.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
static public T New<T>() where T : Event, new()
{
Stack<Event> pool;
if (!eventPools.TryGetValue(typeof(T), out pool))
{
pool = new Stack<Event>(4);
pool.Push(new T());
eventPools[typeof(T)] = pool;
}
if (pool.Count > 0)
return (T)pool.Pop();
else
return new T();
}
/// <summary>
/// Clear all pending events and reset the tick to 0.
/// </summary>
public static void Clear()
{
eventQueue.Clear();
}
/// <summary>
/// Schedule an event for a future tick, and return it.
/// </summary>
/// <returns>The event.</returns>
/// <param name="tick">Tick.</param>
/// <typeparam name="T">The event type parameter.</typeparam>
static public T Schedule<T>(float tick = 0) where T : Event, new()
{
var ev = New<T>();
ev.tick = Time.time + tick;
eventQueue.Push(ev);
return ev;
}
/// <summary>
/// Reschedule an existing event for a future tick, and return it.
/// </summary>
/// <returns>The event.</returns>
/// <param name="tick">Tick.</param>
/// <typeparam name="T">The event type parameter.</typeparam>
static public T Reschedule<T>(T ev, float tick) where T : Event, new()
{
ev.tick = Time.time + tick;
eventQueue.Push(ev);
return ev;
}
/// <summary>
/// Return the simulation model instance for a class.
/// </summary>
/// <typeparam name="T"></typeparam>
static public T GetModel<T>() where T : class, new()
{
return InstanceRegister<T>.instance;
}
/// <summary>
/// Set a simulation model instance for a class.
/// </summary>
/// <typeparam name="T"></typeparam>
static public void SetModel<T>(T instance) where T : class, new()
{
InstanceRegister<T>.instance = instance;
}
/// <summary>
/// Destroy the simulation model instance for a class.
/// </summary>
/// <typeparam name="T"></typeparam>
static public void DestroyModel<T>() where T : class, new()
{
InstanceRegister<T>.instance = null;
}
/// <summary>
/// Tick the simulation. Returns the count of remaining events.
/// If remaining events is zero, the simulation is finished unless events are
/// injected from an external system via a Schedule() call.
/// </summary>
/// <returns></returns>
static public int Tick()
{
var time = Time.time;
var executedEventCount = 0;
while (eventQueue.Count > 0 && eventQueue.Peek().tick <= time)
{
var ev = eventQueue.Pop();
var tick = ev.tick;
ev.ExecuteEvent();
if (ev.tick > tick)
{
//event was rescheduled, so do not return it to the pool.
}
else
{
// Debug.Log($"<color=green>{ev.tick} {ev.GetType().Name}</color>");
ev.Cleanup();
try
{
eventPools[ev.GetType()].Push(ev);
}
catch (KeyNotFoundException)
{
//This really should never happen inside a production build.
Debug.LogError($"No Pool for: {ev.GetType()}");
}
}
executedEventCount++;
}
return eventQueue.Count;
}
}
}
and this is my GameController
using Platformer.Core;
using Platformer.Model;
using UnityEngine;
namespace Platformer.Mechanics
{
/// <summary>
/// This class exposes the the game model in the inspector, and ticks the
/// simulation.
/// </summary>
public class GameController : MonoBehaviour
{
public static GameController Instance { get; private set; }
//This model field is public and can be therefore be modified in the
//inspector.
//The reference actually comes from the InstanceRegister, and is shared
//through the simulation and events. Unity will deserialize over this
//shared reference when the scene loads, allowing the model to be
//conveniently configured inside the inspector.
public PlatformerModel model = Simulation.GetModel<PlatformerModel>();
void Start()
{
Screen.SetResolution(1280, 720, true);
}
void OnEnable()
{
Instance = this;
}
void OnDisable()
{
if (Instance == this) Instance = null;
}
void Update()
{
if (Instance == this) Simulation.Tick();
}
}
}
I was dealing with the same issue. The problem generally begins when we write a custom player instead of using the default.
What you need to do, at least for the 2D Platformer microgame, is open up the GameObject called "GameController" (should be right up at the top) and drag your player* onto the Player field under the GameController component.
*Specifically, the GameObject that has your PlayerController component.
(I really like that Unity is diving into a full event system like Qt, but this Simulation class seems very convoluted and graceless to me. We'll see what I think as I progress with it; but I doubt it's that much more efficient than cached GameObject.Find calls.)
That should solve your problem!
I have matlab script textcreator.m that create some result file output.txt.
And there is some matlab.aplication() reference that "translate" matlab function to c# and some of the code is hard to convert to c# and i decide just run the script i made.
using System;
using System.Collections.Generic;
using System.Text;
MLApp.MLApp matlab = new MLApp.MLApp();
matlab.Execute(#"cd d:\textcreator.m");
How to run matlab script textcreator.m when i click a button on my pc that have Matlab?
You have almost got it, but instead of matlab.Execute("cd d:\textcreator.m"), you should matlab.Execute("cd d:\"), then matlab.Execute("run textcreator.m"). So your code should be:
MLApp.MLApp matlab = new MLApp.MLApp();
matlab.Execute("cd d:\");
matlab.Execute("run textcreator.m");
I have also dug out a simple MLApp wrapper I wrote quite some time ago. Thought it would be useful for you.
class MLWrapper
{
private readonly MLApp.MLApp _mlapp;
public MLWrapper(bool visible = false)
{
_mlapp = new MLApp.MLApp();
if (visible)
ShowConsole();
else
HideConsole();
}
~MLWrapper()
{
Run("close all");
_mlapp.Quit();
}
public void ShowConsole()
{
_mlapp.Visible = 1;
}
public void HideConsole()
{
_mlapp.Visible = 0;
}
/// <summary>
/// Run a MATLAB command.
/// </summary>
/// <returns>Text output displayed in MATLAB console.</returns>
public string Run(string cmd)
{
return _mlapp.Execute(cmd);
}
/// <summary>
/// Run a MATLAB script.
/// </summary>
/// <returns>Text output displayed in MATLAB console.</returns>
public string RunScript(string scriptName)
{
return Run($"run '{scriptName}'");
}
/// <summary>
/// Change MATLAB's current working folder to the specified directory.
/// </summary>
public void CD(string directory)
{
Run($"cd '{directory}'");
}
public object GetVariable(string varName)
{
_mlapp.GetWorkspaceData(varName, "base", out var data);
return data;
}
public void SetVariable(string varName, object value)
{
_mlapp.PutWorkspaceData(varName, "base", value);
}
}
Friends, i'm planning to do a cloud based videoplayback project in unity. In my project, cloud targets are detecting but videos are not playing. I need to do json based cloud recognition to play videos but i don't know how to do that.
This is my code for your reference:
using System;
using UnityEngine;
using Vuforia;
using UnityEngine.UI;
/// <summary>
/// This MonoBehaviour implements the Cloud Reco Event handling for this sample.
/// It registers itself at the CloudRecoBehaviour and is notified of new search results.
/// </summary>
public class SimpleCloudHandler : MonoBehaviour, ICloudRecoEventHandler
{
#region PRIVATE_MEMBER_VARIABLES
// CloudRecoBehaviour reference to avoid lookups
private CloudRecoBehaviour mCloudRecoBehaviour;
// ImageTracker reference to avoid lookups
private ObjectTracker mImageTracker;
private bool mIsScanning = false;
private string mTargetMetadata = "";
private GameObject videoObject;
#endregion // PRIVATE_MEMBER_VARIABLES
#region EXPOSED_PUBLIC_VARIABLES
/// <summary>
/// can be set in the Unity inspector to reference a ImageTargetBehaviour that is used for augmentations of new cloud reco results.
/// </summary>
public ImageTargetBehaviour ImageTargetTemplate;
#endregion
#region UNTIY_MONOBEHAVIOUR_METHODS
/// <summary>
/// register for events at the CloudRecoBehaviour
/// </summary>
void Start()
{
// register this event handler at the cloud reco behaviour
CloudRecoBehaviour cloudRecoBehaviour = GetComponent<CloudRecoBehaviour>();
if (cloudRecoBehaviour)
{
cloudRecoBehaviour.RegisterEventHandler(this);
}
// remember cloudRecoBehaviour for later
mCloudRecoBehaviour = cloudRecoBehaviour;
}
#endregion // UNTIY_MONOBEHAVIOUR_METHODS
#region ICloudRecoEventHandler_IMPLEMENTATION
/// <summary>
/// called when TargetFinder has been initialized successfully
/// </summary>
public void OnInitialized()
{
// get a reference to the Image Tracker, remember it
mImageTracker = (ObjectTracker)TrackerManager.Instance.GetTracker<ObjectTracker>();
}
/// <summary>
/// visualize initialization errors
/// </summary>
public void OnInitError(TargetFinder.InitState initError)
{
}
/// <summary>
/// visualize update errors
/// </summary>
public void OnUpdateError(TargetFinder.UpdateState updateError)
{
}
/// <summary>
/// when we start scanning, unregister Trackable from the ImageTargetTemplate, then delete all trackables
/// </summary>
public void OnStateChanged(bool scanning) {
mIsScanning = scanning;
if (scanning) {
// clear all known trackables
ObjectTracker tracker = TrackerManager.Instance.GetTracker<ObjectTracker> ();
tracker.TargetFinder.ClearTrackables (false);
}
}
/// <summary>
/// Handles new search results
/// </summary>
/// <param name="targetSearchResult"></param>
public void OnNewSearchResult(TargetFinder.TargetSearchResult targetSearchResult)
{
// duplicate the referenced image target
GameObject newImageTarget = Instantiate(ImageTargetTemplate.gameObject) as GameObject;
GameObject augmentation = null;
string model_name = targetSearchResult.MetaData;
if( augmentation != null )
augmentation.transform.parent = newImageTarget.transform;
// enable the new result with the same ImageTargetBehaviour:
//Debug.Log("Metadata value is " + model_name );
//VideoPlaybackBehaviour video = ImageTargetTemplate.gameObject.GetComponentInChildren<VideoPlaybackBehaviour>();
mTargetMetadata = model_name;
if (targetSearchResult.MetaData == "a") {
ImageTargetAbstractBehaviour imageTargetBehaviour = mImageTracker.TargetFinder.EnableTracking (targetSearchResult, newImageTarget);
}
if (!mIsScanning)
{
// stop the target finder
mCloudRecoBehaviour.CloudRecoEnabled = true;
}
}
#endregion // ICloudRecoEventHandler_IMPLEMENTATION
}
I'm using Fiorano's C# support for JMS to publish messages on a topic.
Everything goes fine until the application exits. Then it doesn't actually exit.
I'm assuming that Fiorano is running a foreground thread (but that's a guess on my part.)
Here's a minimal, but complete, example that illustrates the problem:
using System;
using System.Collections;
using System.Diagnostics;
using System.Linq;
using fiorano.csharp.naming;
// Note: Reference to
// Assembly: fmq-csharp-native
// Version: v2.0.50727
// Runtime Version: 10.2.0.10533
namespace NotificationClientTest
{
/// <summary>
/// Main program
/// </summary>
public static class Program
{
/// <summary>
/// Main method
/// </summary>
/// <param name="args">The arguments. If any exist we hang.</param>
public static void Main(string[] args)
{
Report("Enter Main");
TheFioranoHangOnExit(args.Any());
Report("Leave Main");
}
/// <summary>
/// Trigger the problem.
/// </summary>
/// <param name="problem"> If true, trigger the problem </param>
private static void TheFioranoHangOnExit(bool problem)
{
// Initialize queue
var contextProperties = new Hashtable
{
{ FioranoContext.SECURITY_PRINCIPAL, "user" },
{ FioranoContext.SECURITY_CREDENTIALS, "secretPassword" },
{ FioranoContext.PROVIDER_URL, "http://192.168.5.1:1956" },
{ FioranoContext.BACKUP_URLS, "http://192.168.5.2:1956" },
{ FioranoContext.INITIAL_CONTEXT_FACTORY, "fiorano.jms.runtime.naming.FioranoInitialContextFactory" },
};
var namingContext = new FioranoNamingContext(contextProperties);
var topicFactory = namingContext.lookupTCF("PRIMARYTCF");
if (problem)
{
Report("Creating a connection");
var connection = topicFactory.createTopicConnection();
connection.stop(); // I've tried swapping the order of stop and close just in case...
connection.close();
}
else
{
Report("No Connection");
}
namingContext.close();
}
/// <summary>
/// Write to console, write to debug window
/// </summary>
/// <param name="message">What to say</param>
private static void Report(string message)
{
Console.WriteLine(message);
Debug.WriteLine(message);
}
}
}
Running this application
C:\Playground\FioranoHangTest\bin\Debug>NotificationClientTest.exe
Enter Main
No Connection
Leave Main
C:\Playground\FioranoHangTest\bin\Debug>NotificationClientTest.exe oops
Enter Main
Creating a connection
Leave Main
[At this point the program hangs.
^C or Task Manager can kill it.]
This question describes a similar problem encountered in Java with GlassFish's JMS. Does Fiorano/C# have the same problem?
Otherwise, what am I missing?
I found an ugly work-around:
public static void Main(string[] args)
{
Report("Enter Main");
TheFioranoHangOnExit(args.Any());
Report("Leave Main");
// Evict Fiorano Foreground threads.
Environment.Exit(0);
}
Excuse me, I have to go wash my fingers off with lye soap after typing that one.
I'm still hoping for a better answer.
I have a simple query, i am following the tutorial on this link:
http://www.prideparrot.com/blog/archive/2012/12/how_to_create_a_simple_blog_part1#book-unique-identifier
My problem is the author on this tutorial configure ninject in the global.asax file and deleted the ninjectwebcommon.cs file. i am trying to integrate the justblog into my existing asp.netMVC5 application that is using the ninjectwebcommon.cs file.
Any help would be much appreciated.
Did you use Nuget to add Ninject? You'll need a reference to WebActivatorEx for the bootstrapper to work (obviously along with the other required Ninject references). Add a NinjectWebCommon.cs class in your App_Start folder in your project, looking like this:
[assembly: WebActivatorEx.PreApplicationStartMethod(typeof(YourMvcApp.App_Start.NinjectWebCommon), "Start")]
[assembly: WebActivatorEx.ApplicationShutdownMethodAttribute(typeof(YourMvcApp.App_Start.NinjectWebCommon), "Stop")]
namespace YourMvcApp.App_Start
{
using System;
using System.Web;
using Microsoft.Web.Infrastructure.DynamicModuleHelper;
using Ninject;
using Ninject.Web.Common;
public static class NinjectWebCommon
{
private static readonly Bootstrapper bootstrapper = new Bootstrapper();
/// <summary>
/// Starts the application
/// </summary>
public static void Start()
{
DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));
DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));
bootstrapper.Initialize(CreateKernel);
}
/// <summary>
/// Stops the application.
/// </summary>
public static void Stop()
{
bootstrapper.ShutDown();
}
/// <summary>
/// Creates the kernel that will manage your application.
/// </summary>
/// <returns>The created kernel.</returns>
private static IKernel CreateKernel()
{
var kernel = new StandardKernel(); // you'll add modules to the parameter list here
try
{
kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();
//RegisterServices(kernel);
return kernel;
}
catch
{
kernel.Dispose();
throw;
}
}
///// <summary>
///// Load your modules or register your services here!
///// </summary>
///// <param name="kernel">The kernel.</param>
//private static void RegisterServices(IKernel kernel)
//{
//}
}
}