An object reference is required to access non-static member/ Referencing Function

Hello. I have been trying to write a script that references another function from another script. Below is what I have. However when I go to actually reference the function I get this error “An object reference is required to access non-static member”. Any help would be greatly appreciated I have been searching for a while and I still cannot wrap my head around this problem and how I can fix it. Thanks in advance.

	public GameObject LinkToScript;


	public void OnSceneLoaded (Scene scene, LoadSceneMode mode) {

		LinkToScript = GameObject.Find ("Object");
		LinkToScript.GetComponent<OnCrash> ();
    	
OnCrash.Crashed();
	}

Assuming OnCrash is the class of the script you’re trying to reference, you’re attempting to call the Crashed() function from the OnCrash class type itself, which can only be done with static functions. There’s two ways to fix this:

  1. Get a reference to the instance of the OnCrash script in the other GameObject. Reworking your above code, this looks like:

    public GameObject LinkToScript;

    public void OnSceneLoaded (Scene scene, LoadSceneMode mode)
    {
    LinkToScript = GameObject.FInd("Object);
    OnCrash crashScript = LinkToScript.GetComponent();
    crashScript.Crashed();
    }

Side note: If you have access to both objects in the editor (which you very likely do, considering, you’re doing this when the scene loads up), instead of using the slow GameObject.Find() method, you can link the OnCrash script in the editor itself by dragging its gameobject from the hierarchy to a field in your above script’s inspector. Then you can set it up like this:

public OnCrash crashScript;

void Start()
{
	crashScript.Crashed();
}
  1. On the other hand, perhaps you DO want the Crashed() function to be a static method. A public static method of a class can be called from anywhere, without needing a reference to an instance of that class. However, since static methods are part of the class itself rather than instances of the class, they cannot access fields of individual instances of that class. Because of this, they’re typically used for “utility” functions (for example, every function in the built-in Mathf class is a static function).

If your Crashed() function meets these requirements, and if you declare your Crashed() function in your other script to be a public static function, then you don’t need to link anything to your script, and you can reference Crashed() from the OnCrash type directly:

void Start()
{
	OnCrash.Crashed();
}