Game Development Community

SimObject from ID - howto?

by Leslie Young · in Torque Game Engine · 10/14/2007 (11:52 am) · 3 replies

I'm trying to get access to an object from its ID. How do I do this in the engine source?

In my Torque script I make this call...
KBMNet.saveDeck( Deck1.getId() );

The ConsoleMethod looks like this...
ConsoleMethod( KBMNetObject, saveDeck, void, 3, 3, "(deck_obj_id)")
{
// ....
}

Is there another method I could rather use?
I was also thinking of rather called a save function from the Deck object itself.. for example Deck1.save(); but that would result in problems where I need to find a way into my net object again.

#1
10/14/2007 (12:18 pm)
I don't know the underlying class of your deck object, so you'll need to fill in the details, but this will work with minimal changes:

DeckObjectClass * deckObject = dynamic_cast<DeckObjectClass *>(Sim::findObject(argv[2]));

At this point, deckObject will be a pointer to the object within the simulation, if it exists. Make sure to check for it being = NULL before actually using it, since if they do not type in a correct objectID, the dynamic_cast will fail (making the pointer NULL).
#2
10/14/2007 (12:52 pm)
Thanks Stephen, Sim::findObject was what I was looking for ;)
#3
10/14/2007 (1:26 pm)
Another idiom (which I prefer) is:

DeckObjectClass *deckObject = NULL;
if(!Sim::findObject(argv[2], deckObject)
{
   Con::errorf("Failed to find '%s'", argv[2]);
   return false;
}

// Now use deckObject

The call to Sim::findObject assigns the found object to deckObject and returns true. If nothing is found it returns false and you can do error handling (like printing out a "couldn't find" error). Behind the scenes this is all very similar to Stephen's post but it has the added advantage of avoiding having to write the type more than once, and a little bit clearer error-checking path.