- Home /
Access class from all scripts
Is there a way I can call this code from all my scripts:
public class Game : MonoBehaviour {
private static Game _instance;
public static Game instance {
get {
if (_instance == null)
_instance = GameObject.FindObjectOfType<Game> ();
return _instance;
}
}
public void Test() {
Debug.Log("Test");
}
}
like this:
Game.Test();
instead of having to do this:
Game.instance.Test()
//Or
Game g = Object.FindObjectOfType<Game>();
if(g != null)
g.Play();
Answer by Baste · Nov 05, 2014 at 04:10 PM
Yes there is. Make it static, and have the static version call a method on the instance
public static void Test() {
instance.TheActualTest()
}
void TheActualTest() {
Debug.Log("Test");
}
If you do this, you can also let the instance be private, and only access it through public static methods - that usually gives a lot cleaner code.
When trying to call it from another script with this:
Game.Test();
I get an error "BCE0005: $$anonymous$$ identifier: 'Game'"
Nvm, I just placed the script in the Plugins folder :)
@Baste Is there a way to it like this:
//In another script
function Game.OnBeforeSpawn() {
//Some code here
Debug.Log("Test");
}
class script:
public class Game : $$anonymous$$onoBehaviour {
public static void SpawnPlayer(Vector3 pos, GameObject PlayerObject, bool Respawn) {
instance.OnBeforeSpawn ();
GameObject p = Network.Instantiate(PlayerObject, pos, Quaternion.identity,0) as GameObject;
p.name = PlayerPrefs.GetString("Username");
p.tag = "Player";
Debug.Log("Spawned Player");
}
void OnBeforeSpawn() {} //So declare this function from a script. So it would work something like Update(), like a built in function that can be modified.
}
So if the script gets run like this from a third script:
function Start() {
Game.SpawnPlayer(Vector3.zero, PO, false);
}
It would log "Test" to the console and then instantiate a the GameObject and log "Spawned Player" and if I where to have multiple of the first script it would be called no matter what gameobject and script it is in.
Your answer
![](https://koobas.hobune.stream/wayback/20220613170807im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Class instance access to scene? 1 Answer
Coroutine design problem? 3 Answers
My void Start won't work 1 Answer
Call method from attached Gameobject 1 Answer
On Void Called 2 Answers