- Home /
Scripts help
I have a variable, audioHasPlayed, which is in a script called Rotors. I'm trying to access through another script. Is this how I do it?
Note: It compiles but in Unity it says "NullReferenceException: Object reference not set to an instance of an object."
private var rotorScript: Rotors;
private var audioHasPlayed: boolean = rotorScript.audioHasPlayed;
A NullReferenceException is a very common error. It has to do with you trying to access something and there being no object to access to. So, say you make a GameObject variable and not assign the variable, and then have the script try to reference some kind of execution attached another object, it cant find that GameObject you are wanting to manipulate.
In your situation, you are calling for a script with rotorScript.audioHasPlayed;. where is the rotorScript attached? You need to do a GameObject.Find().GetComponent(); to assign the rotorScript variable.
so would this work?
private var rotorscript: rotors = GameObject.Find("FrontRotor").GetComponent(rotors);
private var audioHasPlayed: boolean = rotorscript.audioHasPlayed;
or would this work? since GameObject.Find() has to be called from Start or some other function?
var rotorscript: rotors;
var audioHasPlayed: boolean = rotorscript.audioHasPlayed;
function Start () {
rotorscript = GameObject.Find("FrontRotor").GetComponent(rotors);
}
You should assign the boolean variable after you've assigned the script. You might as well keep the variable audioHasPlayed static and do this from the helo script:
if (rotors.audioHasPlayed) DoSomething();
Answer by NhommeBeurreOne · Aug 15, 2012 at 09:15 PM
You can't access private variables from other script. Also, you may want to take a look at the Reference. Basically, you need to tell on which GameObject the script is attached to find it.
Best Regards
Nbo
Your answer
![](https://koobas.hobune.stream/wayback/20220613075728im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
"Object Reference not set to an instance of an object" 1 Answer
NullReferenceException - Maze Generator Script 1 Answer
How do I reference something from another scene? 0 Answers
How Can i Reference String another Script? 2 Answers
How to reference another script and call a function in C# ? 2 Answers