Jump to content

Recommended Posts

Posted

This is a nice one. I am iterating through a list of gameObjects. I want to know when one of these GameObjects is a Player class (player is a subclass of GameObjects). But the iteration iterates through gameobjects and not players.

 

//GameObject list iteration
for (iter; iter != gameObjects.end(); ++iter)
{
//If the gameobject has sub classtype player....
if(typeid((*iter)) == typeid(Player))
{

 

Is there a nice way to handle this?

Posted

This is generally why I always use entity->SetUserData(this) when inside a class. Then I make a base class like GameObject, which has a pure virtual ToString() and my sub classes override it and return a string that describes that class.

 

class Player
{
public:
virtual string ToString() { return "player"; }
};

 

Then in your loop you cast the object to GameObject* and if not null call ToString() and compare the value to what you are looking for.

 

 

OR

 

You set a key for each entity when loaded and get the key in your loop to compare.

Posted

It should be possible to detect "isSubclassOf" (C# like) by create a variable from the type you want to check, then assignt the iterator value (c++ cast) and check if your variable != null.

 

for (iter =gameObjects.begin(); iter != gameObjects.end(); iter++)
{
Player* playercast = dynamic_cast<Player*>( *iter );
if (playercast != null)
{
// its a player
}
}

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...