- Home /
Static calls to Static GameObject
I have a GameObject called GameManager. I have made it static. It also has DoNotDestroyOnLoad(). Is there a way I can access it by saying GameManager.DoThis() from any scene?
"I have a GameObject called Game$$anonymous$$anager. I have made it static"
Do you mean you ticked Static in the Inspector? In this case, static is not related to program$$anonymous$$g but just inform the engine that this objecst is static as in not moving.
That is exactly what I was thinking. Thanks for the clarification!
Answer by Kiwasi · Nov 10, 2014 at 05:20 AM
This is called the singleton pattern. Its typically done like this.
public GameObject instance;
void Awake (){
if(instance){
Destroy(gameObject);
return;
}
instance = gameObject;
DontDestroyOnLoad(gameObject);
}
You can go one step further and make instance a property that will create the GameObject the first time it is called (lazy loading).
Note that you cannot have a true static GameObject. You can only fake it.
Darn. Was hoping to avoid using a singleton. But thanks :) How would I access this gameObject? By using ScriptName.instance?
Yup. Nothing inherently wrong with a singleton. You can avoid the singleton requirements by using a preloader. But its worth having the singleton, just in case.
Answer by V_IPIN · Nov 10, 2014 at 04:27 AM
Once Try this
public class GameManager : MonoBehaviour {
public static void DoSomeThing(){
Debug.Log("I will Call this method from another script...");
}
}
Another Script
public class AccessMethod : MonoBehaviour {
// Use this for initialization
void Start () {
GameManager.DoSomeThing();
}
}
Yes, this works for a static method, but I want it for a static gameObject. So what I am looking for would require Game$$anonymous$$anager.gameObject.DoSomething(); with the example you provided. I am just trying to access the GameObject directly...not one of its scripts.
Once try this...
public class Game$$anonymous$$anager : $$anonymous$$onoBehaviour {
public static Game$$anonymous$$anager instance;
public GameObject DisableObject;
void Start(){
instance = this;
}
}
public class Access$$anonymous$$ethod : $$anonymous$$onoBehaviour {
// Use this for initialization
void Start () {
Game$$anonymous$$anager.instance.DisableObject.SetActive(false);
}
}