I am trying to get the name of the game object. for that i used

    Debug.Log (gameObject.transform.ToString());

in start. My gameObject name is "PowerupItem_0" and "PowerupItem_1". in console it displayed the gameObject name correctly. then i tried to execute the statement. so i used

    if (gameObject.transform.ToString () == "PowerupItem_0") {
        Debug.Log ("PI_0");
    } else if (gameObject.transform.ToString () == "PowerupItem_1") {
        Debug.Log ("PI_1");
    } else
        Debug.Log ("Oth");

for this coding in console it displayed a message as "oth". i am not understanding why its not printing "PI_0" and "PI_1". anybody please help

Hierarchy tab Debug.Log Console If Statement Console


gameObject.transform.ToString() gives you with transform type. Means (UnityEngine.Transform) is also included in string. You can get GameObject's name simply by calling gameObject.name.

| improve this answer | |

Like Hamza Hasan said the (UnityEngine.Transform) is also a part of the returned string. Of course you could get the name of the GameObject with gameObject.name, but why don't you create a "Powerup_Item" class with a property "Name"? That would be the better solution in my opinion.

| improve this answer | |
  • \$\begingroup\$ Your suggestion is right though, but it is irrelevant to the question. He asked why the if check is not working although it returns the name \$\endgroup\$ – Hamza Hasan Jan 9 '16 at 16:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.