- Home /
How to compare if two gameObjects are the same?
I´m trying to make a game about visual memory. Random a game object appears and after 5 seconds disappear and another one appear. The goal is the player select that game object if is equal to the last one. How can i compare the fist game object and the one that players click? Any suggestions???
Thanks
The main ideia is making a match game with graphic elements! It´s an idea thank's "book".
Answer by yacth_Mon · Apr 19, 2017 at 10:17 AM
Use Object.RefrenceEquals(obj1, obj2)
Like this
if(GameObject.ReferenceEquals( firstGameObject, secondGameObject))
Debug.Log("first and second are the same");
Also you can use to check if it null ? by changing secondGameObject to null.
Read more about ReferenceEquals
Hope this can help you. :)
I run the test on all 3 methods and this has been the fastest. $$anonymous$$uch faster than the others.
Answer by 1Benisin · Jun 05, 2015 at 08:23 AM
Use GameObject.GetInstanceID()
if (firstObj.GetInstanceID() == secondObj.GetInstanceID()) {
// objects are the same instance
}
Answer by Kiwasi · Jul 20, 2014 at 08:35 AM
... can't you use
gameObject == otherGameObject
or am I missing something critical...
I think it's ok, I trust in the GameObject's overriden comparison behaviour.
I can confirm this DOESN'T work - Unity doesn't recognize them as the same even when they are. In the end I gave the objects unique names and compared them later.
You are RONG. the == operator is overloaded as such, meaning it correctly compares two objects with ==:
At the end of the day it seems inconsistent whether the '==' is going to give the correct answer.
But comparing 2 different names/strings is a method that works %100 of the time in my experience. So I recommend it.
It should work, other solutions are for the sake of performance.
Answer by book · Jul 19, 2014 at 11:21 PM
You could maybe give a special name or tag to the different objects.
"Blue" for blue objects and "Red" for red etc.
Then in a script keep storing the name/tag of the last object that was on the screen in a string and then just do a check to see if the last object's tag was the same as the one that the user clicked.
Just an Idea..
Your answer
Follow this Question
Related Questions
How to compare if two gameObjects are the same? 2 Answers
Making a randomizer script for a basic "Runner" game... 1 Answer
How to make objects appear randomly around a spot 2 Answers
Random Time question 2 Answers
Randomly spawn a trigger area 1 Answer