I have a Player object which many other objects in my game are interested in. The camera for instance is one of these objects. When the player dies, I am destroying that object and creating a new one. In the time that the player object is destroyed, errors occur. I don’t want to have if(player){} checks all over my code to prevent these.
- Is there a better design I should be using to prevent this?
- Do you have multiple scripts on multiple object all finding and keeping a reference to the player?
- If I drag in a player prefab as a variable to each of my scripts does that prefab game object reference the single instance of the player which gets spawned at the beginning of the level?
Any help on how this should be designed would be super helpful. Thanks!
Why do you need to Destory() your player?
Why not turn off all colliders and renders associated with your player. Also, if needed, create a gameActive bool, or playerDead bool.
having checks for another object actually existing before interacting with it isn’t necessarily a bad thing, but I’d agree with renman it might need a rethink on destroying the player if you are doing that to respawn it. Not just from a “have to refind the gameobject” point of view but for the wasteful instantiate/destroy also.
I switched it up to Just move the player, via transform pos, back to the last spawn point upon being dead rather than destroying and recreating the player. There’s still the issue of the initial spawning of the player. Is there a way to run some things prior to every other script running? Like I’d want my game manager to kick off first creating the level before everything else gets loaded and starts trying to reference the player. Here’s what I have to do in every script that keeps a reference to the player:
can’t view the link at the moment, but there is a set order to the unit function calls: