Can someone please tell me why i keep getting a nullReferenceExceptionError. I am trying to access a script attatched to the controller gameobject.
public var controller:GameObject;
var getEssenceHandlerComponant:Component = controller.GetComponent("GetEssenceHandler");
function Update() {
}
function LateUpdate () {
var number:float = getEssenceHandlerComponant.lifeEssenceCarrier;
number = Mathf.Floor(number);
gameObject.Find("Value").guiText.text = number.ToString() + "%";
}
It is saying there is a null exception at line 2 of the code. Ive checked my getEssenceHandler script is attached to the controller object.
It seems you cannot reference the a variable if both are not in a method. You have to do this:
public var controller:GameObject;
private var getEssenceHandlerComponant:Component;
function Awake() {
getEssenceHandlerComponant = controller.GetComponent("GetEssenceHandler");
}
function Update() {
//if(getEssenceHandlerComponant.) // gui
}
function LateUpdate () {
var number:float = getEssenceHandlerComponant.lifeEssenceCarrier;
number = Mathf.Floor(number);
gameObject.Find("Value").guiText.text = number.ToString() + "%";
}
You should almost never use strings in GetComponent, nor should you use Component as the type. Also, stick to declaring variables only outside functions, and run code inside functions. Also, don’t use Find every frame in Update, do it once in Start and cache the result.
private var getEssenceHandlerComponent : GetEssenceHandler;
private var valueGUIText : GUIText;
function Start () {
getEssenceHandlerComponent = controller.GetComponent(GetEssenceHandler);
valueGUIText = GameObject.Find("Value").GUIText;
}
If getEssenceHandlerComponent is null, that means the controller object doesn’t have that component. Also, in JS, public is default for variables, if you want private you have to specify it. You don’t need to write ToString if you’re concatenating a number with a string, and you’re using some unnecessary steps.
Are you sure that the component’s name is spelled exactly as you have it listed?
Double check that the component is attached to the object you’re trying to access.
Finally, you might try moving that GetComponent() call into an Awake() function, like so:
var otherGuy : OtherGuyComponent;
function Awake()
{
otherGuy = GetComponent(OtherGuyComponent);
}
I personally don’t recommend using GetComponent with string arguments. It works, but doesn’t expose programming errors as early and only gives you generic “component” reference, which usually isn’t ideal.