- Home /
Object reference not set to an instance of an object
I have two scripts.
The 'Health' script component, placed on the 'Player' reloads the scene if the health drops below 0.
public var startHealth : float = 10f;
public var health : float = 10f;
public var sceneToLoad : String = "Test";
function Start()
{
health = startHealth;
}
function Update()
{
if (health <= 0f )
LevelReset();
}
function LevelReset()
{
Application.LoadLevel (sceneToLoad);
}
And the 'CollisionDamage' script, attached to the 'deathball' object, applies damage to the player upon collision.
var playerObject : GameObject;
var damage : float = 10f;
var oldHealth;
var newHealth;
function OnCollisionEnter (col : Collision)
{
if (col.gameObject.name == "Player")
{
print ("Collision");
oldHealth = playerObject.GetComponent("Health");
oldHealth = playerObject.Health.health;
newHealth = oldHealth - damage;
playerObject.Health.health = newHealth;
}
}
My problem is that upon colliding the two objects, I receive this error:
NullReferenceException: Object reference not set to an instance of an object Boo.Lang.Runtime.RuntimeServices.GetDispatcher (System.Object target, System.String cacheKeyName, System.Type[] cacheKeyTypes, Boo.Lang.Runtime.DynamicDispatching.DispatcherFactory factory) Boo.Lang.Runtime.RuntimeServices.GetDispatcher (System.Object target, System.Object[] args, System.String cacheKeyName, Boo.Lang.Runtime.DynamicDispatching.DispatcherFactory factory) Boo.Lang.Runtime.RuntimeServices.GetProperty (System.Object target, System.String name) UnityScript.Lang.UnityRuntimeServices.GetProperty (System.Object target, System.String name) CollisionDamage.OnCollisionEnter (UnityEngine.Collision col) (at Assets/Scripts/Damage/CollisionDamage.js:13)
Answer by UNZoOM · Apr 02, 2015 at 07:37 PM
// Its not able to recognize the health script because of the double quotes.
Change OnCollision to this ,
var HealthRefScript;
function OnCollisionEnter (col : Collision)
{
if (col.gameObject.name == "Player")
{
print ("Collision");
HealthRefScript = playerObject.GetComponent(Health);
oldHealth = HealthRefScript.health;
newHealth = oldHealth - damage;
HealthRefScript.health = newHealth;
}
}