- Home /
How to compare GameObjects in an array?
I am quite new to Unity and I am making a program for my school project. It is doing to be a classic puzzle game style of matching specific items in a row in order clear them. I have figured how to clear the objects but my only problem is how to detect if two items next to each other are the same. I have used a 2D array which has stored each type of cloned prefab in its corresponding grid position but have found out using commands like:
if (Array[x, y] == Array[x-1, y])
doesn't work for some reason.
Anyone have any ideas how i could overcome this it would be greatly appreciated.
Answer by fblast1 · May 06, 2020 at 01:20 PM
Well, this checks the reference of each element if they refer to same gameobject https://docs.unity3d.com/ScriptReference/GameObject.html
if you need to check the element prefab type itself use Tags for each type you have and assign them then compare the tags itself https://docs.unity3d.com/Manual/Tags.html
Regards
Just to expand on this: in your described case of a matching game, tags are the way to go. Tags will not always be the right answer to comparing two objects though. They work best when you only have a few different types of object. Too many tags gets confusing.
As an alternative to Tags, you could check to see if both objects had the same components with GetComponent<> or you could ask if they had a specific component and then compare the values of that component to see if they're the same. It all depends on how complex your game is and how specific you want to be with comparing two things.
If you wanted to reduce the number of GetComponent<> calls, you could swap out your array from GameObject to the component you were comparing.
When you use ==, you're actually calling a method to compare the two things either side of the ==. It's possible to write your own version of this method and some objects in Unity have a custom method for comparing them already. By default though, it asks if the two things you're comparing are literally the same object; as in, "do they both occupy the same space in your RA$$anonymous$$?", hence your current problem. Each instance of your cloned prefab is a different thing, stored in a different place in RA$$anonymous$$.
Thanks a lot using tags helped a lot as i only have 6 different items that need to be checked. This has helped me overcome a problem I have been stuck on for way too long.