# Error when using GetComponent (Object reference not set to an instance of an object)

I'm using a textmesh to check variables in real time. Thing is if I use AddComponent within Update(), it obviously starts spamming and slows the game. If I try with GetComponent the error is the following:

NullReferenceException: Object reference not set to an instance of an object

DebugCombo.Update() (at Assets/DebugCombo.js:9)

which points to the text.text assignment.

This is the script from DebugCombo.js, from which I call the Combo class (from Combo.js)

#pragma strict

public class DebugCombo extends MonoBehaviour{

function Update () {
var text = gameObject.GetComponent(TextMesh);
var combo = gameObject.GetComponent(Combo);

text.text = "Current: "+ Time.time +" | Limit: " + combo.comboTime;
}

}


How do I get rid of this error?

• I'm not going to post this as an answer because I'm unsure, but when declaring a variable, you need to also say what type it is. Try using var text:TextMesh = gameObject.GetComponent(TextMesh); and var combo:Combo = gameObject.GetComponent(Combo);. Does this fix it? Apr 22 '14 at 9:01
• Eh, if you're reading this, come join the gamedev chatroom for some instant help :D chat.stackexchange.com/rooms/19/game-development Apr 22 '14 at 9:09

You seem not to have a TextMesh component in your game object, and you are not checking if GetComponent method has returned any. You can add it once at runtime if it doesn't exist:

var text = gameObject.GetComponent(TextMesh);
if( text == null )
{

Or to make it better, you can make var text a private class variable to cache it, and not to call GetComponent all the time.
The second way, is to make text and combo a public class variables, and then drag and drop the proper instances in the editor. Then, you wouldn't have to call any Add/GetComponent calls at runtime, because you would already have them attached.
Anyway, you should always check if GetComponent has returned something, and if not you should call Debug.LogError("Your error message here") to avoid NullPointer exception and application crash.