I'm creating a space shooter (think Space Invaders or Galaga) where the GameManager persists between scenes but the player and enemies don't. I need to access a boolean value from the player and enemies to define when and how the game should end. The PlayerController
script contains a playerDead
variable (attached to the Player
GameObject
) to tell the GameManager
if the player has died and a enemiesDead
variable to tell if all enemies have died.
Because the GameManager
persists but the others don't, it loses the references when a new level is loaded. I tried to have the GameManager
find the script references dynamically, to no avail. It always errors with Object reference not set to an instance of an object
when a new level is loaded.
I've tried to get them with GameObject.FindGameObjectWithTag()
and then using GetComponent<ScriptName>()
to get the script and the variable in it. It compiles nicely and everything seems dandy, but then there's still no object reference. Am I just doing it wrong?
So how can I reference a script and get a value from it without even touching the Inspector?
EDIT:
Below is some code (everything else except the essential is scrapped) from the GameManager
script, I tried to use Object.FindObjectsOfType()
like this:
GameObject player;
GameObject enemies;
void Awake()
{
DontDestroyOnLoad (gameObject);
}
void Start ()
{
Reinitialize ();
}
void Update ()
{
if (enemies.GetComponent<EnemyGrid>().enemiesDead == true)
{
gameEnd = true;
}
if (player.GetComponent<PlayerController>().playerDead == true)
{
gameEnd = true;
}
}
void Reinitialize()
{
player = Object.FindObjectOfType(typeof(PlayerController)) as GameObject;
enemies = Object.FindObjectOfType (typeof(EnemyGrid)) as GameObject;
}
But there's still no object reference. My intention was to run the Reinitialize()
funtion each time a new scene was loaded, so that way the GameManager
would grab the new objects each time.
Player
and theEnemyGrid
(in which individual enemy prefabs are instantiated) objects always in each scene from the start andGameManager
would grab them when a scene was loaded. \$\endgroup\$