- Home /
AnimationEvent NullReferenceException
I was working on a script to add an animation to a weapon, and when I added the animation event to the timeline I started to randomly get this error "NullReferenceException: Object reference not set to an instance of an object Melee.AttackDamage () (at Assets/Scripts/Melee.js:28)" Everything else works fine, but the minute I try to add the Event I get the error. It doesn't affect the game, but I'm still wondering why it happens.
#pragma strict
var TheDamage : int = 50;
var Distance : float;
var MaxDistance : float = 1.5;
var TheSystem : Transform;
function Update ()
{
if(Input.GetButtonDown("Fire1"))
{
animation.Play("Attack");
}
}
function AttackDamage ()
{
var hit : RaycastHit;
if(Physics.Raycast (TheSystem.transform.position, TheSystem.transform.TransformDirection(Vector3.forward),hit))
{
Distance = hit.distance;
}
if (Distance < MaxDistance)
{
hit.transform.SendMessage("ApplyDamage", TheDamage, SendMessageOptions.DontRequireReceiver);
}
}
&&
#pragma strict
var Health = 100;
function Update ()
{
if (Health <= 0)
{
Dead ();
}
}
function ApplyDamage (TheDamage: int)
{
Health -= TheDamage;
}
function Dead ()
{
Destroy (gameObject);
}
Answer by Fox-Handler · May 16, 2014 at 11:52 AM
Alright I think I fixed it. I don't think I'll be using send message again if I'm able. Basically just had the if statement call a static function.
var TheDamage : int = 50;
var Distance : float;
var MaxDistance : float = 1.5;
var TheSystem : Transform;
function Update ()
{
if(Input.GetButtonDown("Fire1"))
{
animation.Play("Attack");
}
}
function AttackDamage ()
{
var hit : RaycastHit;
if(Physics.Raycast (TheSystem.transform.position, TheSystem.transform.TransformDirection(Vector3.forward),hit))
{
Distance = hit.distance;
}
if (Distance < MaxDistance)
{
EnemyLogic.ApplyDamage(TheDamage);
}
}
&&
#pragma strict
static var Health = 100;
function Update ()
{
if (Health <= 0)
{
Dead ();
}
}
static function ApplyDamage (TheDamage: int)
{
Health -= TheDamage;
}
function Dead ()
{
Destroy (gameObject);
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613145154im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
NullReferenceException when looking at target in an Editor class (CustomEditor) 2 Answers
Why can't I get my scripts to communicate without getting a NullReferenceException? 1 Answer
Editor script executing before variable updated 1 Answer
Why does my Bullet prefab go missing from my gun script when destroyed? 1 Answer
NullReferenceException for reasons I don't understand. 1 Answer