NullReferenceException: Fox not changing to walk after attacking

I get a null reference exception (object reference not set to an instance of an object)in my attacker.cs script, causing my fox not to change back to walking after it has destroyed its target. Strangely, the lizard is working fine but not the fox.

My attacker.cs is below, and im currently using Unity 5 for this so not sure if it makes a difference. Thanks!

using UnityEngine;
using System.Collections;

[RequireComponent(typeof (Rigidbody2D))]
public class Attacker : MonoBehaviour {

    [Range (-1f, 1.5f)] public float walkSpeed;

    private GameObject CurrentTarget;	
    private Animator anim;

	// Use this for initialization
	void Start () {
	Rigidbody2D myRigidBody = gameObject.AddComponent<Rigidbody2D>();
	myRigidBody.isKinematic = true;
	anim = gameObject.GetComponent<Animator>();
	}

	// Update is called once per frame
	void Update ()
	{
		transform.Translate (Vector3.left * walkSpeed * Time.deltaTime);
		if (!CurrentTarget) {
		anim.SetBool("isAttacking", false);
		}
	}

	void OnTriggerEnter2D ()
	{Debug.Log (name + "Trigger Enter");
	}

	void CurrentSpeed (float speed)
	{walkSpeed = speed;
	}
	//called from animator at the time of the actual attack
	void StrikeCurrentTarget (float damage)
	{
		if (CurrentTarget) {
			health health = CurrentTarget.GetComponent<health> ();
			if (health) {health.DealDamage(damage);
			}
		}
	}

	public void Attack (GameObject obj)
	{CurrentTarget = obj;
	}
}

thanks!

I had exactly the same thing on unity 4 - The problem turned out to be RigidBody2D. I had it defined in the attackers script for all attackers, and again on the inspector for the fox. Removing one of these methods solved the problem.

make sure your parameter variable is named the same thing in both attackers.

Privacy & Terms