Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Game Development How to Make a Video Game Game Audio Additional Audio Scripting

Mark VonGyer
Mark VonGyer
21,214 Points

Null Reference Exception - Bird Movement.Update()

I have a problem with my code but I can't see the problem.

null reference exception- object reference not set to an instance of an object birdMovement.Update().

My code is as follows:

using UnityEngine;
using System.Collections;

public class birdMovement : MonoBehaviour {

[SerializeField]
private Transform target;
private NavMeshAgent birdAgent;
private Animator birdAnimator;
[SerializeField]
private RandomSoundPlayer birdFootsteps;
// Use this for initialization
void Start () {
    birdAgent = GetComponent<NavMeshAgent> ();
    birdAnimator = GetComponent<Animator> ();

}

// Update is called once per frame
void Update () {
    birdAgent.SetDestination (target.position);

    float speed = birdAgent.velocity.magnitude;
    birdAnimator.SetFloat ("Speed", speed);

    if (speed > 0f) {
        birdFootsteps.enabled = true;
    }
    else
    {
        birdFootsteps.enabled = false;
    }
}

}

2 Answers

Jefferson Lessa
Jefferson Lessa
5,684 Points

Likely, you still need to add the birdFootsteps object on your script, from the inspector. Select the Bird object, and check the inspector to see if the field "Bird Footsteps" says "None".

When Unity throws an error, the error also says to you the line that the error happened. That can help you to find what is wrong in an instant.

If you still don't know what caused the error, check the error line, and tell that here so we can help.

Hi Mark,

I haven't got to this point in the course yet but my first thought was to make sure that you have correctly added the target transform to the script in the Unity GUI, as target is not set in your code.

Was there any more detail in the error message?

Otherwise just make sure that you have a NavMeshAgent & Animator component on the gameobject to which you are adding the script.