- Home /
How to instantiate many different prefabs from one prefab?
Hi, Let me make my question clearer: I have a prefab, and added a reference of it in my code. Now, I know that if I'll try to instantiate many times times with different values each time, each iteration would overwrite the previews and in the end all the prefabs that I instantiated would have the same values, because they all point to the same address on the heap.
So, I would like to know if there is a way to make a new prefab each time, with new address, so if I change the values in one of them, it won't change it in all of them.
I appreciate any effort to help.
Answer by Team2Studio · Sep 09, 2020 at 01:47 PM
Hi @gigos22,
If you instantiate a prefab you should be able to change any value of the instantiated object without changing the values for any other instantiated prefabs. Just make sure that the object you change the values of, is the instantiated prefab, and not the reference prefab in your code.
@Team2Studio OK so I think I understand my problem now, I'll say it you verify / falsify my understanding:
Right now I'm assigning the values to my reference prefab, and then I'm instantiating it. But what I actually need to do is to first instantiate my reference and then assign the values I want for it. Right? Am I understanding correctly?
@gigos22 yes, first instantiate the prefab => GameObject someObject = Instantiate(prefab) as GameObject, and then change values for the instantiated object "someObject", which is an instance of your prefab. Only the instantiated object"s values will be changed and nothing else.
Edit: It was a problem in my code logic, so it works! I can't thank you enough for you help!! I appreciate it very much.
So I tried it.. And it doesn't work for some reason. What I am doing is putting the object that returns from Instantiate() inside an array, like this:
rowsArray[i][j] = Instantiate(prefab, parent.transform);
And then I'm sending it to a function that fills the text components in that prefab, like this:
FillRow(rowsArray[i][j]);
But eventually all of my objects has the same values in their text components.