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 :)
asked Dec 09 '09 at 01:21 PM
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.
answered Dec 09 '09 at 02:04 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:
Be sure to check out the docs on Arrays. And then each Card script would have something like the following:
answered Dec 09 '09 at 02:02 PM