NullReferenceException: Object reference not set to an instance of an object

Hi. I’m making my first game on unity and I have just run into this error. Whenever I run my game I recieve this error: “NullReferenceException: Object reference not set to an instance of an object
Enemy_AI.SetDestination (UnityEngine.Vector3 dest) (at Assets/scripts/Enemy_AI.cs:82)
Enemy_AI.Chasing () (at Assets/scripts/Enemy_AI.cs:41)
Enemy_AI.Update () (at Assets/scripts/Enemy_AI.cs:36)”.

This is the script I wrote. It is an enemy AI script for an active ragdoll:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;

public class Enemy_AI : MonoBehaviour
{
public Transform player;
public LayerMask ground, isplayer;

Vector3 walkpoint;
bool walkpointset;
public float walkpointRange;

public float timebetweenattack;
bool attacked;

public float sightRange, attackRange;
bool insight, playerinattackrange;

public ConfigurableJoint spinejoint;

Animator anim;

// Start is called before the first frame update
void Awake()
{}

// Update is called once per frame
void Update()
{
insight = Physics.CheckSphere(transform.position, sightRange, isplayer);
playerinattackrange = Physics.CheckSphere(transform.position, attackRange, isplayer);

if (!insight && !playerinattackrange) Patrolling();
if (insight && !playerinattackrange) Chasing();
}

void Chasing()
{
SetDestination(player.position);
}

void Patrolling()
{
if (!walkpointset) SearchWalkPoint();

if (walkpointset)
{
SetDestination(walkpoint);
}

Vector3 distanceToWalkPoint = transform.position - walkpoint;

if (distanceToWalkPoint.magnitude < 1f)
{
walkpointset = false;
anim.SetBool("walking", false);
}
}

void SearchWalkPoint()
{
float randomz = Random.Range(-walkpointRange, walkpointRange);
float randomx = Random.Range(-walkpointRange, walkpointRange);

walkpoint = new Vector3(transform.position.x + randomx,transform.position.y, transform.position.z + randomz);

if (Physics.Raycast(walkpoint, -transform.up, ground))
{
walkpointset = true;
}

}

void SetDestination(Vector3 dest)
{
Vector3 direction = dest - transform.position;
float angle = Mathf.Atan2(direction.z, direction.x) * Mathf.Rad2Deg;
spinejoint.targetRotation = Quaternion.Euler(0f, angle, 0f);

anim.SetBool("walking", true);
}
}

Thank you in advance.

You never assign anything to your field “anim”.

Either serialise the field (make it public or add the SerializeField attribute) and assign it in the inspector, or use GetComponent in Awake/Start to assign a value to it.

Did you get animator from GameObject?
Use GetComponent or SerializeField / public

It does not even matter remotely what this script is doing. Why?

Because the answer for NullRef is always the same… ALWAYS. It is the single most common error ever.

Don’t waste your life spinning around and round on this error. Instead, learn how to fix it fast… it’s EASY!!

Some notes on how to fix a NullReferenceException error in Unity3D

  • also known as: Unassigned Reference Exception
  • also known as: Missing Reference Exception
  • also known as: Object reference not set to an instance of an object

http://plbm.com/?p=221

The basic steps outlined above are:

  • Identify what is null
  • Identify why it is null
  • Fix that.

Expect to see this error a LOT. It’s easily the most common thing to do when working. Learn how to fix it rapidly. It’s easy. See the above link for more tips.

You need to figure out HOW that variable is supposed to get its initial value. There are many ways in Unity. In order of likelihood, it might be ONE of the following:

  • drag it in using the inspector
  • code inside this script initializes it
  • some OTHER external code initializes it
  • ? something else?

This is the kind of mindset and thinking process you need to bring to this problem:

https://discussions.unity.com/t/814091/4

Step by step, break it down, find the problem.

Here is a clean analogy of the actual underlying problem of a null reference exception:

https://discussions.unity.com/t/840647/7

3 Likes

Thank you all.

IM SO CONFUSED
ive got an error like this too but different :frowning:

Can’t help you fix it if we can’t see the code :wink:

Make a thread and post your code and errors.

Be sure to paste your code using the forum’s ‘insert code’ button when you’re making a new thread so we can see the line numbers.

It’s only three steps. Which one are you struggling with?

How to fix a NullReferenceException error

https://forum.unity.com/threads/how-to-fix-a-nullreferenceexception-error.1230297/

Three steps to success:

  • Identify what is null ← don’t go anywhere until you have this one done
  • Identify why it is null
  • Fix that

Estou tendo esse mesmo problema e não consigo descobrir porque, aqui esta meu código e a print da minha tela, alguém pode me dizer o que esta errado?

usando System.Collections;
usando System.Collections.Generic;
usando UnityEngine;
usando UnityEngine.UI;

classe pública NameTransfer: MonoBehaviour
{
    string pública nomePlayer;
    campo de entrada GameObject público;
    public GameObject textDisplay;

    public void SalvarNome()
    {
       nomePlayer = inputField.GetComponent<Text>().text;
       textDisplay.GetComponent<Text>().text = "Bem Vindo a aventura" + nomePlayer;
    }




}
[/código]

I am having the same issue with null, sos…
“NullReferenceException: Obiect reference not set to an instance of an obiect
movement.ProcessMouseRotation () (at Assets/Scripts/movement.cs:45)”
I am making the player object in fps game move with mouse movement, but I believe its not in the code yet ill share it in hopes to get urgent help…

public class movement : MonoBehaviour
{
    [SerializeField] float moveSpeed = 5f;
    [SerializeField] float mouseSensitivity = 100f;

    float xThrow;
    float zThrow;
    float xRotation = 0f;

    void Start()
    {
        // Lock the cursor to the center of the screen
        Cursor.lockState = CursorLockMode.Locked;
    }

    void Update()
    {
        controls();
        ProcessMouseRotation();
    }

    private void controls()
    {
        xThrow = Input.GetAxis("Horizontal");
        zThrow = Input.GetAxis("Vertical");

        float xValue = xThrow * moveSpeed * Time.deltaTime;
        float zValue = zThrow * moveSpeed * Time.deltaTime;
        transform.Translate(xValue, 0, zValue);
    }

    private void ProcessMouseRotation()
    {
        float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
        float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;

        xRotation -= mouseY;
        xRotation = Mathf.Clamp(xRotation, -90f, 90f);

        transform.localRotation = Quaternion.Euler(0f, transform.localRotation.eulerAngles.y + mouseX, 0f);
        Camera.main.transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
    }

}

i dont think this is possible
because error is in line 45 but there is no line 45

“at Assets/Scripts/movement.cs:45”

i believe problem is in inputField.GetComponent().text; because there is no inputField.

add this to top
public InputField inputField;

then attach your inputfield in unity editor
it should be working now

Check that you have a camera with the MainCamera tag.

thank you so much for your effort, it was the tag indeed, much appreciated.