Can't reference a variable from another script

Here are my scripts:
Here is where I define my variable “coins”

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class MouseController : MonoBehaviour
{
public float jetpackForce = 75.0f;
private Rigidbody2D playerRigidbody;
public float forwardMovementSpeed = 3.0f;
public Transform groundCheckTransform;
private bool isGrounded;
public LayerMask groundCheckLayerMask;
private Animator mouseAnimator;
public ParticleSystem jetpack;
private bool isDead = false;
public int coins = 0; //*********************************************************
public Text coinsCollectedLabel;
public Button restartButton;
public AudioClip coinCollectSound;
public AudioSource jetpackAudio;
public AudioSource footstepsAudio;
public parallaxScroll parallax;
public Image black;
public Animator anim;
public bool isStopped = false;
// Start is called before the first frame update
void Start()

And here is my attempt at referencing that variable from another script:

Using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class Level1CompleteScript : MonoBehaviour
{
public Button restartButton;
public Text message;
private int cheeseCount;
private string cheeseCountString;
void Start()
{

MouseController mouseController = GetComponent();
cheeseCount = mouseController.coins; //**************************************************************
cheeseCountString = cheeseCount.ToString();
message.text = "You collected “+ cheeseCountString + " Cheese!”;
Debug.Log(“made it”);
}
public void RestartGame()
{
SceneManager.LoadScene(“Main”);
}
}

The line with the asterisks throws an error “Object reference not set to an instance of an object”. But when I type mouseController. it pulls up coins as an option. So it is obviously seeing it.

Lookie that, the most common error in the entire world!

The answer is always the same… ALWAYS. It is the single most common error ever. Don’t waste your life on this problem. Instead, learn how to fix it fast… it’s EASY!!

Some notes on how to fix a NullReferenceException error in Unity3D

  • also known as: Unassigned Reference Exception
  • also known as: Missing Reference Exception

http://plbm.com/?p=221

The basic steps outlined above are:

  • Identify what is null
  • Identify why it is null
  • Fix that.

Expect to see this error a LOT. It’s easily the most common thing to do when working. Learn how to fix it rapidly. It’s easy. See the above link for more tips.

This is the kind of mindset and thinking process you need to bring to this problem:

https://discussions.unity.com/t/814091/4

Step by step, break it down, find the problem.

I used the same structure in a different place and it worked fine there. I wasn’t assigning an object to something, it is a simple variable. When I typed mouseController. and then looked at the options that pop up, it shows all the variables in that script, making it look like the line of code was making the connection to the script. It turns out the problem is that to reference a variable from a different script you must declare it Static. I’m new at coding. I spent hours researching this. Thanks for the “you are not trying hard enough” not so helpful comment.

2 Likes

“to reference a variable from a different script you must declare it Static”

Not correct. You can reference public variables in any script, whether declared static or not. Often you’ll have one master script which tells a bunch of other scripts what to do, sends and receives values, etc. These can be non-static variables…in fact, static variables are typically rare and used for things like score, which need to persist across scenes.

If you declare a variable static, you can reference it directly from any script:

scriptName.variable = 5;

If it’s not static, you need to get a reference to that script via the GameObject it’s attached to. Scripts are Components, and the type of Component is the name of the script. So they’re kind of unusual in that regard, unlike Rigidbodies, Colliders, etc.

public ScriptName myScript;

// Drag GameObject with script (that has the variable you want to access) attached into slot in Inspector.

void Start() {
myScript=GetComponent<ScriptName>();
}

myScript.variable = 5;

You can also call methods (must be marked public):
myScript.method();

Hope that helps. I spent quite a while figuring this out when I started coding in Unity as well, trying to wrap my brain around the difference with static, non-static, scripts attached to GameObjects, that scripts are Components, etc. The answer actually is simple, but I had a rough time finding it.

Plus, inappropriate use of ‘static’ makes your code hard to maintain, hard to debug, and far less flexible. It should be used with care, and only when fully understood.

You may think it makes things “easier” now, but just wait until you need to fix or hack around places where it’s overused…