- Home /
NullReferanceException When Enemy touches Player
Hello - Will here, After creating a short script (supplied bellow) I have noticed an error occurring: When the enemy touches the player, rather than taking the 10 health away, an error message is broadcasted; "NullReferanceException: Object Referance not set to an instance of an object." I am assuming this is what is stopping the health from being taken away. Many Thanks, Will.
var health = 100;
var healthcount : Transform;
var enemy : Transform;
function Update () {
healthcount.transform.GetComponent.<TextMesh>().text = health.ToString();
}
function OnTriggerEnter (other : Collider) {
if (other.Collider.enemy){
health -= 10;
}
}
Answer by Daemonhahn · Jul 25, 2017 at 03:55 PM
Because you are getting the component in Update, it is likely not available yet.
Instead cache this reference in Start so you dont get it each time.
Like this:
Text healthText;
void Start()
{
healthText = healthcount.transform.GetComponent.<TextMesh>();
}
void Update()
{
healthText.text = health.ToString();
}
I attempted a change: var health = 100; var healthcount : Transform; var enemy : Transform; var healthText; function Start() { healthText = healthcount.transform.GetComponent.(); }
function Update() { healthText.text = health.ToString(); }
function OnTriggerEnter (other : Collider) { if (other.Collider.enemy){ health -= 10; } }
However I still get the error, you used void, I tried my best to translate to JavaScript.
But you are trying to get (other.Collider.enemy) and yet you do not do a get component to get the enemy? How are you getting the .enemy, as it looks to me like it would give a null reference as there is no reference for it.
Also try learning c#, you will find it more robust and a lot more tutorials use c# than javascript.
something like
Enemy enemy = other.Collider.GetComponent<Enemy>();
if(enemy)
{
// rest of code
}
Answer by wizbit · Jul 25, 2017 at 03:52 PM
Hey BadwolfX
i believe it may be that you have not set the within your healthcount.transform.GetComponent.().text = health.ToString().
https://docs.unity3d.com/ScriptReference/GameObject.GetComponent.html
I recommend learning C# as javascript is not widely used for Unity anymore and has many caveats
Your answer
Follow this Question
Related Questions
Linking Image to item list 1 Answer
Can anyone just read this over? for my 2d runner? 1 Answer
SphereCast doesn't work when I increase the radius. 1 Answer
Coin collection script (not working) 1 Answer
Roll a Ball wont roll? 1 Answer