Comparing game objects

I am trying to compare two GameObjects to see if they are the same:

GameObject foo;
void Start(){
	foo = Instantiate(SomeGameObject);
}
void CompareGO(GameObject bar){
	if(foo == bar)
	{
		DoSomethingElse();
	}	
}

This doesn’t work, because since I am instantiating the GameObjects at runtime, bar might be called “GameObject (Clone)” and == seems to only compare the name value of the GameObjects. Short of manually setting the name of the GameObject, are there any easier ways to do this?

Hi, I'm in a similar problem. Beginner in Unity3D. I want to check the target position movement and load a win screen. This does not work. Could you please help me ? targetpos= Player2.transform.position. if(Player.transform.position == targetpos) { Debug.Log ("Came Here"); Application.LoadLevel("WinScreen"); }

Hi @mogambo! I converted your reply to a comment. Please, don't post your question as an answer to another (if similar) question. You can make a new question if you want, which is more likely to get you replies.

why <= 23f? that does not make any sense.

2 Answers

2

Hi I’m not sure what your exactly but your code should work if you want to compare to see if the objects are the same instance. If you want to check to see if they are of the same type(from the same prefab) try use Object.GetType to compare the type of the object. I’m not sure if it will work because I’m I don’t fully understand how prefabs work but give it a try.

GameObject foo;
void Start(){
    foo = Instantiate(SomeGameObject);
}
void CompareGO(GameObject bar){
    if(foo.GetType() == bar.GetType())
    {
        DoSomethingElse();
    }   
}

Edit: You say that the when comparing the GameObjects it compares by name. Is this true? So it doesn’t compare them by reference?

Edit2: I just tested the above code and it doesn’t work. GetType just returns GameObject. If comparing 2 GameObjects does compare by name and you want to see if they are the same instance you could use the instanceID to check if they are the same.

GameObject foo;
void Start(){
    foo = Instantiate(SomeGameObject);
}
void CompareGO(GameObject bar){
    if(foo.GetInstanceID() == bar.GetInstanceID())
        DoSomethingElse();
    }   
}

It looks like it works if you do:

if(foo.name == bar.name)