Referencing scripts in class vs in method

Viewed 39

This is a super basic question, i'm sure, but I can't find an answer. So I notice that whenever another script is referenced at the top of a class you have to drag it into the Unity inspector slot as well or else it will return a null reference exception. For Example:

public class ExampleClass : MonoBehaviour
{
   public ScriptExample1 scriptexample1;

   public void Method()
   {
      scriptexample1.score++;
   }
}

However, if the script is referenced as a method parameter you do not have to drag it into the inspector slot. For Example:

public class ExampleClass : MonoBehaviour
{


   public void Method(ScriptExample2 scriptexample2)
   {
      scriptexample2.score++;
   }
}

Can someone please explain to me why ScriptExample1 needs the script to be dragged into the inspector slot and ScriptExample2 doesn't?

Thank you,

1 Answers

Object references need to come from somewhere.

When you define a public field, Unity lists it in the inspector window, where dragging a component will set that reference for you through the designer.

Another way to initialize a field's reference is to fetch a component in your OnStart callback, and explicitly set it - this works by traversing the GameObject components and finding one of the correct type (not finding the component might throw an error right there, or leave the field null to blow up later, I'm not sure):

public SomeComponent someComponent;

public void OnStart()
{
    someComponent = GetComponent<SomeComponent>();
}

caveat: air-code from memory for illustrative purposes

When you receive a component as a method parameter, you're deferring the responsibility of this initialization to the caller: if the caller does not initialize it or otherwise passes a null reference, consuming it will throw a NullReferenceException all the same.

Related