I'm trying to understand how to setup my Unity prefabs and scripts to dynamically spawn a series of "encounters", with each encounter containing several GameObject
s.
For example, imagine spawning the next several portions of an infinite-runner level. One encounter is a ramp, the other encounter is a pit with some coins.
This is what I am currently doing:
- A global
SceneManager
script has a handle to anEncounterFactory
prefab. When needed, theSceneManager
will begin constructing the game world. - The
EncounterFactory
prefab contains a script that has a methodSpawnRandomEncounter
. TheEncounterFactory
also contains handles to several other prefabs for the objects that can be found in an encounter. - The
SpawnRandomEncounter
method uses the prefabs linked toEncounterFactory
and builds the expectedGameObjects
.
So when building out a new "encounter", the SceneManager
clones the EncounterFactory
(which serves as the parent object for the full encounter), and then calls SpawnRandomEncounter
to build out the child objects.
This seems suboptimal. First, I need to have myriad prefabs for each thing that could be spawned. It also requires a meta-prefab to EncounterFactory
. That is, a prefab who just allows me to spawn other prefabs.
Is there a better way to dynamically build out a game world or level in Unity? Or is it prefabs upon prefabs upon prefabs?
For example, I'm aware that I can find an existing object by name. (e.g. find EncounterTemplate5
and clone that.) However, that requires that EncounterTemplate5
exist in the game world. (So it can be cloned.)