- Home /
null object reference
I'm trying to access a variable in other script but it only gives me:
NullReferenceException: Object reference not set to an instance of an object
I'm trying to access 'sanity' variable from my slenderAI script.
I'm trying to access them with this code:
using UnityEngine;
using System.Collections;
public class StaticScreen : MonoBehaviour {
public slenderAI script;
void Start(){
script = GetComponent<slenderAI>();
}
void Update(){
if(script.sanity < 100){
Debug.Log("Hi");
}
}
}
is the slenderAI script on the same object as the StaticScreen script?
Put your sanity variable public or do an accessor and it will work.
public int sanity;
OR
private int m_sanity;
public int Sanity
{
get{ return m_sanity; }
}
Answer by Programmer-Tau · Nov 03, 2013 at 03:34 PM
You mentioned in the above comment that slenderAI is not on the same object. If that's the case, script is being set to null inside Start(), since GetComponent() will return null.
If you setting the script variable in the inspector, then you just need to remove that line in Start(), I believe. If you are not setting script in the inspector, then you need some other way to get a reference to it.
I'm assigning the gameObject with the slenderAI script on the inspector but always when i start the game it puts the object to "none" and gives me the error. I tried taking it of Start() but no luck.
You can attach slenderAI on the same object and call GetComponent(), if that's an option. Otherwise, it seems the root of the problem is the fact that the slenderAI script becomes "none" at the start of the game. Not sure why that's happening though...
I can't attach it to the main camera or the Slenderman becomes buggy.
Hmmm, then I think you need to figure out why the assignment to the gameObject becomes "none". I think we've moved past the scope of this current question.