So I want my code to lower down the healthbar if my player gets hit by a gameobject called Enemy
and I get this error
NullReferenceException: Object reference not set to an instance of an object
Collision2.OnCollisionEnter (UnityEngine.Collision c) (at Assets/Scripts/Collision2.js:35)
I would like to know what this error means exactly
Here’s my code
#pragma strict
var healthBurnSpeed: float;
var haveHealth:boolean;
var healthAmount: float;
var GUI:HealthBar2;
function Start ()
{
GUI = GameObject.FindWithTag("GUI").GetComponent(HealthBar2);
}
function OnCollisionEnter(c:Collision)
{
if (c.gameObject.name == "Enemy" )
{
//currentHealth -= 15.5;
Debug.Log("hit");
}
healthAmount -= (healthBurnSpeed*Time.deltaTime);
if(healthAmount <=0)
{
healthAmount = 0;
haveHealth = false;
}
GUI.UpdateHealthMeter(healthAmount);
}
Here is my other Code
var healthMeter: GUITexture;
var healthMeterStartingWidth:float;
function Start ()
{
healthMeterStartingWidth = healthMeter.pixelInset.width;
}
function UpdateHealthMeter(newHealthAmount:float)
{
healthMeter.pixelInset.width = healthMeterStartingWidth * (newHealthAmount* .01);
}
I changed the tag GUI, but I think it’s not working because I’m using OnCollisionEnter function instead of function Update(). But I could be wrong… I dunno why the health bar doesn’t go down in game.
Ok here’s my question. Is there a way to use an OnEnterCollision function within an Update function? Because the GUI will not update on screen without an Update function. When I try using an OnEnterCollision within an Update function it creates errors. All I want is if player collides with enemy then update gui health bar
You have to place the code in OnEnterCollision. Could you post your current code and the exact error message you are getting. It is important that you always check the very first error message if there is more than one.
It seems that the health bar is not found in your Start function. EliteMossy posted code to illustrate how you can find it out.
Of course, but this is only called when it enters a collision. It doesn’t decrease the health while the collision takes place, but only when it enters the collision.