- Home /
How can I set a sprite to a bunch of clones?
Hi, again. Here another question. I got 6 clones each clone has 2 gameObject with a spriteRender. And now I want to change my sprites. But it changes only 1 clone and only 1 sprite. Maybe someone can help me.
public Sprite[] SpritePipes;
void Start() {
Sprite mySpritePipes = SpritePipes[0];
for(float x = 0; x< 7.8f; x = x + 1.3f)
{
Instantiate(pipesStructur, new Vector3(x + 3, 0.9f, 0), Quaternion.identity);
test = GameObject.Find("Pipes(Clone)").GetComponentInChildren<SpriteRenderer>();
Debug.Log (GameObject.Find("Pipes(Clone)"));
test.sprite = mySpritePipes;
}
}
Answer by xortrox · Apr 22, 2014 at 10:24 PM
I would place all instantiated pipes in a List or Array for future access, or maybe just their SpriteRenderer (so that you don't waste performance on GetcomponentInChildren)
Thank you for your comment, but I dont see how it affects the result
Here you are only affecting the sprite of one object because GameObject.Find("Pipes(Clone)") most likely finds the first instance of Pipes(Clone), you could however do GameObject g = (GameObject)Instantiate(pipesStructur, new Vector3(x + 3, 0.9f, 0), Quaternion.identity);
g.sprite = mySpritePipes;
So that you get the proper reference.
50 % success! Now 6 sprites are right. my new script:
for(float x = 0; x< 7.8f; x = x + 1.3f)
{
Instantiate(pipesStructur, new Vector3(x + 3, 0.9f, 0), Quaternion.identity);
}
GameObject g = (GameObject)Instantiate(pipesStructur, new Vector3(x + 3, 0.9f, 0), Quaternion.identity);) doesnt work!
But this:
GameObject[] pipes = GameObject.FindGameObjectsWithTag("Pipe");
foreach(GameObject pipe in pipes)
{
pipe.GetComponentInChildren<SpriteRenderer>().sprite = mySpritePipes;
}
How is it possible that all sprites are changed?
haha Im stupid. It works now! well I changed my childs Tags "Scene_Pipe" and now its done! ("Pipe" is already in use)
GameObject[] pipes = GameObject.FindGameObjectsWithTag("Scene_Pipe"); ...
thanks for helping me!
Don't feel stupid, it's common to make mistakes, no problem.
Your answer
Follow this Question
Related Questions
Problem with Line Renderer 1 Answer
Distribute terrain in zones 3 Answers
Multiple Cars not working 1 Answer
Instantiated Sprite is not rendering. 1 Answer
Instantiating multiple sprites and assigning different colors for each 1 Answer