Search Unity

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

Discussion in 'Scripting' started by Username123r, Aug 9, 2021.

  1. Username123r

    Username123r

    Joined:
    Feb 27, 2021
    Posts:
    8
    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:
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.AI;
    5.  
    6. public class Enemy_AI : MonoBehaviour
    7. {
    8. public Transform player;
    9. public LayerMask ground, isplayer;
    10.  
    11. Vector3 walkpoint;
    12. bool walkpointset;
    13. public float walkpointRange;
    14.  
    15. public float timebetweenattack;
    16. bool attacked;
    17.  
    18. public float sightRange, attackRange;
    19. bool insight, playerinattackrange;
    20.  
    21. public ConfigurableJoint spinejoint;
    22.  
    23. Animator anim;
    24.  
    25. // Start is called before the first frame update
    26. void Awake()
    27. {}
    28.  
    29. // Update is called once per frame
    30. void Update()
    31. {
    32. insight = Physics.CheckSphere(transform.position, sightRange, isplayer);
    33. playerinattackrange = Physics.CheckSphere(transform.position, attackRange, isplayer);
    34.  
    35. if (!insight && !playerinattackrange) Patrolling();
    36. if (insight && !playerinattackrange) Chasing();
    37. }
    38.  
    39. void Chasing()
    40. {
    41. SetDestination(player.position);
    42. }
    43.  
    44. void Patrolling()
    45. {
    46. if (!walkpointset) SearchWalkPoint();
    47.  
    48. if (walkpointset)
    49. {
    50. SetDestination(walkpoint);
    51. }
    52.  
    53. Vector3 distanceToWalkPoint = transform.position - walkpoint;
    54.  
    55. if (distanceToWalkPoint.magnitude < 1f)
    56. {
    57. walkpointset = false;
    58. anim.SetBool("walking", false);
    59. }
    60. }
    61.  
    62. void SearchWalkPoint()
    63. {
    64. float randomz = Random.Range(-walkpointRange, walkpointRange);
    65. float randomx = Random.Range(-walkpointRange, walkpointRange);
    66.  
    67. walkpoint = new Vector3(transform.position.x + randomx,transform.position.y, transform.position.z + randomz);
    68.  
    69. if (Physics.Raycast(walkpoint, -transform.up, ground))
    70. {
    71. walkpointset = true;
    72. }
    73.  
    74. }
    75.  
    76. void SetDestination(Vector3 dest)
    77. {
    78. Vector3 direction = dest - transform.position;
    79. float angle = Mathf.Atan2(direction.z, direction.x) * Mathf.Rad2Deg;
    80. spinejoint.targetRotation = Quaternion.Euler(0f, angle, 0f);
    81.  
    82. anim.SetBool("walking", true);
    83. }
    84. }
    Thank you in advance.
     
    Last edited: Aug 9, 2021
  2. bobisgod234

    bobisgod234

    Joined:
    Nov 15, 2016
    Posts:
    1,042
    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.
     
  3. DevGulpi

    DevGulpi

    Joined:
    Aug 6, 2021
    Posts:
    17
    Did you get animator from GameObject?
    Use GetComponent<Animator> or SerializeField / public
     
  4. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,697
    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://forum.unity.com/threads/why-do-my-music-ignore-the-sliders.993849/#post-6453695

    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://forum.unity.com/threads/nul...n-instance-of-an-object.1108865/#post-7137032
     
    Ryland21, wessi01 and Nightmarer666 like this.
  5. Username123r

    Username123r

    Joined:
    Feb 27, 2021
    Posts:
    8
    Thank you all.
     
  6. boofyt1

    boofyt1

    Joined:
    Aug 23, 2021
    Posts:
    4
    IM SO CONFUSED
    ive got an error like this too but different :(
     
  7. mopthrow

    mopthrow

    Joined:
    May 8, 2020
    Posts:
    348
    Can't help you fix it if we can't see the code ;)

    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.
     
  8. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,697
  9. unity_E908153A07E34DD431FB

    unity_E908153A07E34DD431FB

    Joined:
    Mar 22, 2023
    Posts:
    1
    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?





    Code (CSharp):
    1. usando System.Collections;
    2. usando System.Collections.Generic;
    3. usando UnityEngine;
    4. usando UnityEngine.UI;
    5.  
    6. classe pública NameTransfer: MonoBehaviour
    7. {
    8.     string pública nomePlayer;
    9.     campo de entrada GameObject público;
    10.     public GameObject textDisplay;
    11.  
    12.     public void SalvarNome()
    13.     {
    14.        nomePlayer = inputField.GetComponent<Text>().text;
    15.        textDisplay.GetComponent<Text>().text = "Bem Vindo a aventura" + nomePlayer;
    16.     }
    17.  
    18.  
    19.  
    20.  
    21. }
    22. [/código]
     

    Attached Files: