UserData Usage

Topics: Developer Forum
Sep 27, 2010 at 11:01 AM

I'm having a bit of trouble getting to grips with the use of UserData. I've got it working, but I can't imagine this is the most elegant solution:


// UserData Class just holds  single bool
class UserData {

  public bool bWhatever = false;

  public UserData(){
  }
}

 

// Crate class, and constructor
class Crate
{
public Crate()
        {           
            _box = FixtureFactory.CreateRectangle(_world, width, height, density, boxLocation);
            _box.Body.BodyType = BodyType.Dynamic;


            UserData u = new UserData();
            u.bWhatever = true; // change the bool to check it's working
            _box.UserData = u;
             

        }
}

 

Then to test it at the moment I'm calling:

 

// somewhere in Update
UserData u = (UserData)_box.UserData;
if (u.bWhatever)
{
      DebugViewManager.Instance._debugView.DrawString(20, 40, string.Format("UserData Working"));
}

As I said, I can't imagine all these temp UserDatas and casting is strictly necessary. Ideally I guess I'd just be using:

 

_box.UserData.bWhatever = true;

Any help would be much appreciated. :)

Sep 27, 2010 at 11:15 AM
Edited Sep 27, 2010 at 11:15 AM

What I do (and I think that most of the people here does too) is to assign to the userdata the whole class. For example:

 

// Crate class, and constructor
class Crate
{
public Crate()
        {           
            _box = FixtureFactory.CreateRectangle(_world, width, height, density, boxLocation);
            _box.Body.BodyType = BodyType.Dynamic;

            _box.UserData = this;
        }
}

 

Then for testing it you can do:

 

// somewhere in Update
Crate crate = _box.UserData as Crate;
if (!(u is null))
{
      DebugViewManager.Instance._debugView.DrawString(20, 40, string.Format("UserData Working"));
}

 

Sep 27, 2010 at 12:32 PM

Ah, works a charm. Many thanks :)