Home > Net >  Is there a way to keep references to game objects from prefabs in Unity?
Is there a way to keep references to game objects from prefabs in Unity?

Time:07-19

I am making a game where I have to spawn enemies. Currently I have the enemy saved as a prefab so I can instantiate them when I need to, but it looses its references to the scene when I spawn them. Is it possible to keep the references? If not, what are some alternative ways of spawning things that do not require prefabs?

CodePudding user response:

Is it possible to keep the references?

No, you cannot save a reference to an in-scene object in a .prefab file.

If not, what are some alternative ways of spawning things that do not require prefabs?

The best way to go about this would be to:

  1. Place an instance of the prefab you're using into the scene.
  2. Deactivate the root GameObject of that prefab instance (with the check box in the upper-left of the Inspector when it's selected).
  3. Give your spawner a reference to that in-scene prefab instance and use that as the first argument in your Object.Instantiate call.
  4. Call .SetActive(true) on the new instance's root GameObjects as they're spawned.

This will allow you to continue using prefabs but also have the ability to reference scene-specific objects. An alternative would be to do what you're trying, call GetComponent<T> on the new instances, and passing along the references to each new instance but that'd be much slower and less robust (as the reference requirements change, the spawning code would also need to change).

  • Related