How to assign prefabs to a GameObject at run time

I have a variable of type GameObject that I am actually assigning (dragging) a prefab using the Inspector. My goal is to use 6 different prefabs and assign them randomly to such a GameObject. One solution I found is to declare 6 GameObject variables and drag its own prefab to each one of them, but I would like to use only one GameObject variable and randomly assign one of the 6 prefabs in code at run-time. How can I achieve this funcionality?

I will very much appreciate your help.

Assigning prefabs at runtime doesn’t make sense. Actually you can use Resources folder and Resources.Load() method to bring any content to your game at runtime. You should tell more about what you want to achieve.

1 Like

I would put all of those prefabs in a sub folder of your Resources Folder, than use Resources.LoadAll to dump all of those prefabs into a array, once that is done you can randomly choose prefabs out of the array by using a Random.Range for its index

1 Like