Setting objects up for collision detection

Topics: Developer Forum
Oct 23, 2013 at 6:43 AM
Edited Oct 23, 2013 at 6:50 AM
Hello, why my UserData gives me NullReferenceException with body in fixtureB while it find correct UserData from body in FixtureA

my setup:
protected override void LoadContent()
    // creating a ball
    Body ball = BodyFactory.CreateCircle(_world, 0.02f, 1f);
    ball.OnCollision += new OnCollisionEventHandler(OnCollision);
    ball.UserData = "ball";
    // creating a ground
    Body ground = BodyFactory.CreateRectangle(world, 1f, 0.1f, 1f);
    ground.UserData = "tramboline";

private bool OnCollision(Fixture fixtureA, Fixture fixtureB, Contact contact)
    Body body1 = fixtureA.Body;
    Body body2 = fixtureB.Body;
    System.Diagnostics.Debug.WriteLine(body1.UserData); // ball
    System.Diagnostics.Debug.WriteLine(body2.UserData); // NullReferenceException !?!
    return true;
Thanks in advance.
Oct 23, 2013 at 2:17 PM
Do you only have two bodies? Or are there more bodies you are not showing here. I had the same occur before when my OnCollision was triggered by a body where UserData was not set. Clearly this is also happening to you.

For the sake of being "clean" I would suggest a ToString on the UserData, since UserData is of the type object

Also you can replace the following line:
ball.OnCollision += new OnCollisionEventHandler(OnCollision);
ball.OnCollision += OnCollision;
Oct 24, 2013 at 5:35 AM
Edited Oct 24, 2013 at 10:27 AM
Yes there are more bodies than those two. All of them have been created by the same way and all of them have UserData set up. And of course I had there ToString() with UserData ;)

Edit: well the ground wasn't in the correct place for the farseer engine while I managed to render it to the screen in correct place. :D And now when I moved the ground to the correct place for the farseer engine it finally works. Thanks.
Oct 24, 2013 at 9:28 AM
There must be one body you are not setting the UserData of. Can we see more code? That would make it easier to find the problem. Because other than saying "You must have missed one" I dont know what else I can do without seeing the code. Often when I keep blindly staring at a problem I know is simple I get a buddy of mine to look at it. Even though he never used XNA/MonoGame or Farseer he often sees it.