- Home /
Get all sprites of the prefab in order and change their sprite
I have the following prefab:
I need to get all of the b's (b1, b2, b3...) of the Result prefab. I approached this problem with giving each b a Tag 'resultBall' and now I can access these objects in code like this:
var sprites : GameObject [] = GameObject.FindGameObjectsWithTag("resultBall");
for (var i = 0; i<3; i++){
var spritePath = "Textures/Sprite_" + i;
sprites[i].GetComponent(SpriteRenderer).sprite = Resources.Load(spritePath, Sprite);
}
However, I'm having a problem with
var sprites : GameObject [] = GameObject.FindGameObjectsWithTag("resultBall");
The thing is that in this object I don't seem to get b objects in "order". I would need them to be b1, b2, ..., b20.
So, did I go about this totally wrong? Could I have used (I tried but to no luck) something like first a reference to Results prefab and then (somehow) get his children, or something like that?
Any help or nudge in the right direction is welcome!
you can sort your array by name
http://answers.unity3d.com/questions/155694/sort-list-alphabetically.html
Answer by Hitman666 · Feb 02, 2015 at 12:53 PM
Thanks to fafase's comment I was able to sort my objects based on the name. But, since I had names like b1, b2, ..., b20 I had to rename them to 1, 2, ..., 20. And then I used the following compare function:
function CompareCondition(itemA: GameObject, itemB: GameObject) {
var valA : int = parseInt(itemA.name);
var valB : int = parseInt(itemB.name);
if (valA > valB) return 1;
if (valA < valB) return -1;
return 0;
}
Which I then used in the following way to sort:
sprites.Sort(sprites, CompareCondition);