- Home /
Finding multiple objects by the same tag as to place them in one array?
I want to make a card game. Every card object will behave the same, so I created a prefab. I created a main object that listens for the cards values and adds them to one array. Index of this array is the number of the card. So if I have 3 cards they will will have numbers: 0, 1 and 2. And here is my problem, with these indexes. I don't want to change them every time I add a new prefab to the scene from the editor. I thought about to answers to my problem: 1) When the prefab is put onto the scene its index number goes up by 1. But that's probably difficult and in order to work it should tracks index number of the last card put. 2) On Start () I wanted to search for every object the has tag: Card and put them all into the array, and then access them.
Neither of these I don't know how to implement. Or maybe there is simpler solution? Thanks :)
Answer by Bampf · Dec 09, 2009 at 02:04 PM
It's straightforward to find all objects with a particular tag. See the documentation for GameObject.FindObjectsWithTag. The example (JavaScript) code is probably very close to what you need.
If you are new to Unity's arrays, see this handy overview page. FindObjectsWithTag returns an array, and this may be exactly the array you need. But if you want to filter or sort the cards somehow, you can also see in the sample code how to walk the list of GameObjects you got back.
Answer by burnumd · Dec 09, 2009 at 02:02 PM
I can't say I'm entirely certain I understand what your end goal is, but if you're not instantiating cards at run-time, you can use GameObject.FindGameObjectsWithTag(tag : String) to get an array of GameObjects with the same tag. If you do use this approach, you should only do it in Start() (or some other method that gets called only once). If you want to instantiate cards at run-time and monitor them with some global entity, I suggest you add a method to that monitor script that allows cards to register with it, along the lines of:
var allCards : Array = new Array ();
function RegisterCard (card : Card) : void { allCards.Add(card); }
Be sure to check out the docs on Arrays. And then each Card script would have something like the following:
function Start () : void {
var cardMonitor : CardMonitor = GameObject.FindObjectOfType(CardMonitor); //Where "CardMonitor" is whatever the script is that keeps track of cards;
if (cardMonitor) {
cardMonitor.RegisterCard(this);
}
}
Thanks. It's also very helpful. For now I'm Using unity as an editor to prototypye, but afterwards for sure your method will be great!