- Home /
NullReferenceException in a wrapper
Hi,
I'm integrating Newton physics engine inside unity, everything works perfectly simulation wise, but I'm facing a strange error happening randomly during running.
While the simulation going on it will stop and throw an exception:
NullReferenceException: Object reference not set to an instance of an object
NewtonNet.NewtonBody.ApplyForceAndTorque (IntPtr unused, Single timestep, Int32 threadIndex) (at Assets/Plugins/NewtonNet.cs:208)
NewtonNet.NewtonWorld.Update (Single timestep) (at Assets/Plugins/NewtonNet.cs:109)
NewtonNet.NewtonWorld.Iterate (Single fps, Int32 iterations) (at Assets/Plugins/NewtonNet.cs:123)
Main.Update () (at Assets/Main.cs:146)
Newton uses a callback to apply forces and torques, and it calls it every iteration. I wrap this callback to call C# delegate function this way:
public class NewtonBody : IDisposable
{
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
delegate void ApplyForceAndTorqueCallback(IntPtr body, float timestep, int threadIndex);
[DllImport(Common.NewtonDLL)]
static extern void NewtonBodySetForceAndTorqueCallback(IntPtr bodyPtr, ApplyForceAndTorqueCallback callback);
public IntPtr bodyPtr;
public delegate void ForceAndTorqueHandler(NewtonBody sender, float timestep, int threadIndex);
public event ForceAndTorqueHandler ForceAndTorqueCallback;
public void ApplyForceAndTorque(IntPtr unused, float timestep, int threadIndex)
{
if (ForceAndTorqueCallback != null)
{
ForceAndTorqueCallback(this, timestep, threadIndex);
}
}
public NewtonBody(IntPtr bodyPtr)
{
this.bodyPtr = bodyPtr;
NewtonBodySetForceAndTorqueCallback(this.bodyPtr, ApplyForceAndTorque);
}
}
In the main script I declare the event method like this:
void ApplyGravity(NewtonBody body, float timestep, int threadIndex)
{
body.SetForce(new [] { 0f, -9.8f * body.Mass, 0f, 0f });
}
I kind of desperate, I tried everything but nothing works. I read around it's the GC that frees some unmanaged memory but I can't tell which??
Please help! Thanks!
Your answer
![](https://koobas.hobune.stream/wayback/20220611232950im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
How do i instantiate a Vector3[] ?? 2 Answers
Photon Network instantiate problem when Master changes 0 Answers