Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

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?

share|improve this question
    
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? –  Chris Apr 22 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 –  Chris Apr 22 at 9:09
add comment

1 Answer

up vote 1 down vote accepted

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 )
{
    text = gameObject.AddComponent(TextMesh);
}

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.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.