I have random world generation in my game. some parts of the world are made from custom prefabs that I would like to access and spawn. I have 100+ prefabs I don’t want to individually place them on the inspector page of my script. So can I access a folder and randomly pick a gameobject/prefab from that folder to spawn?
Currently, for testing I have a random number generator and a gamobject connected to each possible number. so I would just find that object that I connected to that number and spawn that. but that means a lot of game objects in the scripts and a long list of if else (or switch statements). can someone give me advice when dealing with so many prefabs? thank you SO much in advance
Make a scriptable object that stores all these game objects in a collection. Then you just make a random number within the bounds of the length of this collection, and use that to pull a random game object out.
I think he said…
For me this means Resources.LoadAll<T>("MySubdirectory/")
but I know Spiney differs.
I do it in this dynamic UI demo (attached), which loads an arbitrary number of sprites out of a given resources folder. You can do the same with Prefabs if you prefer, just use Resources.LoadAll<GameObject>( "MyPrefabs/")
.
Be sure you read the docs on Resources.LoadAll!!!
Fair cop.
Mind you, no sane person should be click-dragging anything more than a single reference. If you want to reference large numbers of objects, use editor code!
You could easily write a context [MenuItem]
that lets you select a folder and grabs every valid reference from said folder.
I take your point, but it just seems so often you just have a giant directory and your mental use case is simply, “Hey dude, I want you to use ALL this stuff…” that’s what I heard in my mind when I read OP’s post.
Interestingly where I work we are taking more nuanced approach to exposing everything in the Unity editor. We went way towards lots of exposure and now we’re coming back to a more moderate ground backed more by automatic ways of finding stuff, or various predefines, just for sanity and safety and fewer moving parts, fewer serialized things.
And we’re breaking them up more too which is awesome, lots of little ScriptableObjects make me smile when you have to actually author stuff!
I do like my scriptable objects.
Just the use case of ‘I need to reference lots of things at once’ does come up plenty in my projects, such as look-up tables namely for save/load purposes. No way, Jose, am I doing that by hand, so that’s where editor tools come in.
Naturally addons like Odin Inspector make this a lot more frictionless.