Instantiate an array of prefabs, and call a function in each prefab.
So I have an array set up for my prefabs and instantiate them, then after I spawn each prefab I want to call a function with a parameter. However all the prefabs are set to the last function called.
public GameObject Number;
int num;
const int width = 7;
const int height = 5;
GameObject[,] newNumber;
void Start ()
{
GameObject[,] newNumber = new GameObject[width, height];
var rand = new System.Random();
for (int j = 0; j < height; j++)
{
for (int i = 0; i < width; i++)
{
Vector2 pos = Camera.main.ScreenToWorldPoint(new Vector2(Screen.width * (0.2f + 0.1f * i), Screen.height * (1 + 0.15f * j)));
newNumber[i,j] = (GameObject)Instantiate(Number, pos, Quaternion.identity);
num = rand.Next(1, 6);
Debug.Log(num);
newNumber[i,j].GetComponent<Number>().initialize(num);
}
}
}
Code in prefab:
public void initialize(int no)
{
Debug.Log("initialized");
currentRenderer = this.GetComponent<SpriteRenderer>();
if (no == 1)
{
currentRenderer.sprite = number1;
number = 1;
}
else if (no == 2)
{
currentRenderer.sprite = number2;
number = 2;
}
else if (no == 3)
{
currentRenderer.sprite = number4;
number = 4;
}
else if (no == 4)
{
currentRenderer.sprite = number6;
number = 6;
}
else if (no == 5)
{
currentRenderer.sprite = number8;
number = 8;
}
}
it looks like you are already calling a function on your component("Number") on this line. newNumber[i,j].GetComponent().initialize(num);
perhaps I misunderstand. I also don't really understand what you mean by "all prefab are set to last function called".
because I want to send or initialize all of my prefabs to a random number. however say the last prefab created is send a 5, all of my prefabs are set to 5. even though the logged random numbers are all different So whenever I initialize a prefab in the array with a random number, it sets all of the prefabs to that number. Is there any way to individually set each prefab in the array to a separate number.
it looks like you are setting the number in your initialize function, but we don't have the code for that. Can you edit the question, and add it?
ah yes, that was it, thanks alot mate, didn't think about that
Your answer
![](https://koobas.hobune.stream/wayback/20220612070644im_/https://answers.unity.com/themes/thub/images/avi.jpg)