I need to instantiate different gameObjects of different shapes and sizes on top of the left third and the right third of a table, and all this objects need to be random every time the scene loads. I have a library of around 80 GO but the most I'll instantiate, for now, is 30. All the instantiated GO have to be different, that means no duplicates.

I thought that maybe I could create 30 empty gameObjects on the table, where I want to instantiate them in random, but I'm not sure if this is the most intelligent way to do it. Is there any other way?

Also, since I have a library of GO so large, would it be possible to load the folder in the script instead of defining a list and populating it in the editor?

I'm a bit new at coding for Unity, but I'm an experienced programmer.


There are multiple ways of doing the instantiation itself:

  • You could place the 30 empty gameobject as you wish in the level and then spawn objects as children of those empty gameobjects. Signature: public static Object Instantiate(Object original, Transform parent);
  • You can place the 30 empty gameobjects, and just use their transform when spawning your objects (this way doesn't require any kind of hierarchy). Signature: public static Object Instantiate(Object original, Vector3 position, Quaternion rotation);
  • (You could also programmatically compute the transform of each object, that's a valid option as well)

When it comes to scanning a given path to find all assets, take a look at the AssetDatabase.FindAssets helper: https://docs.unity3d.com/ScriptReference/AssetDatabase.FindAssets.html (You can even filter with specifics asset labels!)

To avoid copying the output list of FindAssets to shuffle it, you can generate a list of randomized indexes using Linq, and then simplify iterate on this index list:

    Random rnd = new Random();
    List<int> indexes = Enumerable.Range(0, 30).OrderBy((item)=> rnd.Next()).ToList();



Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.