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:
- Place an instance of the prefab you're using into the scene.
- Deactivate the root
GameObject
of that prefab instance (with the check box in the upper-left of the Inspector when it's selected). - Give your spawner a reference to that in-scene prefab instance and use that as the first argument in your
Object.Instantiate
call. - Call
.SetActive(true)
on the new instance's rootGameObject
s 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).