- Home /
How to access a game object that wasn't destroyed on load?
I have a game object: GameManager, that I want to access from all classes. I've set it in Start() to not be destroyed on load (here is my start function for gamemanager):
public void Start(){
DontDestroyOnLoad (this);
SaveLoad.Save ();
levelTimes = new float[20];
SaveLoad.Load ();
}
But, I can't seem to access it by using gameobject.Find() in my GUI text class(not an actual GUI text object but my own custom GUI text class) here's the code for that:
using UnityEngine;
using System.Collections;
public class GUITextScript : MonoBehaviour {
public float posX;
public float posY;
public float sizeX;
public float sizeY;
Vector3 thisposition;
GameWideScript gamescript;
PlayerControl player;
public string content;
// Use this for initialization
void Start () {
gamescript = GameObject.Find ("GameManager").GetComponent<GameWideScript>();
player = GameObject.Find ("character").GetComponent <PlayerControl>();
}
It throws a NullReferenceException when I try to get the gamemanager object. WHat am I doing wrong?
Can you see it when it's running in the scene? If yes, is the name of the object definitely "Game$$anonymous$$anager" and has "GameWideScript" attached to it? If not, then it is either not in the scene or it is getting destroyed somewhere.
Answer by fafase · Aug 12, 2014 at 06:56 PM
Despite the fact that it should work, I often do in the same situation with this:
gamescript = (GameWideScript)FindObjectOfType(typeof(GameWideScript));
and it always works.