Piyush Damania
Piyush Damania

Reputation: 47

comparing name of gameobject to its parent name

Here is my code:

GameObject no=GameObject.Find("LevelButton");
GameObject noparent=GameObject.Find("LevelPHwithrect (" + (i + 1) + ")");

The problem is that I am able to find the gameobjects, but when I call

if(no.transform.parent.name==noparent.transform.name)
{
    //do something
}

I get an error saying null reference, even when it's finding the object and I have set parent of no to noparent.

Please forgive me if there are errors in this post, as this is my first day on stack overflow.

Upvotes: 1

Views: 881

Answers (2)

trojanfoe
trojanfoe

Reputation: 122458

Use the name property of the GameObject, not Transform. Also code defensively and check for null:

if (no != null && noparent != null && no.name == noparent.name)
{
    //do something
}

Upvotes: 1

Derlin
Derlin

Reputation: 9881

If you have a script attached to the "no" gameobject, try to use:

this.gameObject.name == this.gameObject.transform.parent.gameObject.name

GameObject.Find is kind of dangerous, since you can easily misspell or change the name of the gameobject in the Unity Interface and forget to change it in code. May I ask why you need this snippet ?

Upvotes: 0

Related Questions