TransWikia.com

Instantiate random different gameObjects in specific spaces?

Game Development Asked by HaPK on November 2, 2021

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.

One Answer

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();

Cheers!

Answered by tooomg on November 2, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP