Search Unity

  1. We are migrating the Unity Forums to Unity Discussions. On July 12, the Unity Forums will become read-only. On July 15, Unity Discussions will become read-only until July 18, when the new design and the migrated forum contents will go live. Read our full announcement for more information and let us know if you have any questions.

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:
    39,571
    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:
    350
    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:
    39,571
  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:

  10. wonderfulsandy

    wonderfulsandy

    Joined:
    Mar 1, 2024
    Posts:
    2
    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..
    Code (CSharp):
    1. public class movement : MonoBehaviour
    2. {
    3.     [SerializeField] float moveSpeed = 5f;
    4.     [SerializeField] float mouseSensitivity = 100f;
    5.  
    6.     float xThrow;
    7.     float zThrow;
    8.     float xRotation = 0f;
    9.  
    10.     void Start()
    11.     {
    12.         // Lock the cursor to the center of the screen
    13.         Cursor.lockState = CursorLockMode.Locked;
    14.     }
    15.  
    16.     void Update()
    17.     {
    18.         controls();
    19.         ProcessMouseRotation();
    20.     }
    21.  
    22.     private void controls()
    23.     {
    24.         xThrow = Input.GetAxis("Horizontal");
    25.         zThrow = Input.GetAxis("Vertical");
    26.  
    27.         float xValue = xThrow * moveSpeed * Time.deltaTime;
    28.         float zValue = zThrow * moveSpeed * Time.deltaTime;
    29.         transform.Translate(xValue, 0, zValue);
    30.     }
    31.  
    32.     private void ProcessMouseRotation()
    33.     {
    34.         float mouseX = Input.GetAxis("Mouse X") * mouseSensitivity * Time.deltaTime;
    35.         float mouseY = Input.GetAxis("Mouse Y") * mouseSensitivity * Time.deltaTime;
    36.  
    37.         xRotation -= mouseY;
    38.         xRotation = Mathf.Clamp(xRotation, -90f, 90f);
    39.  
    40.         transform.localRotation = Quaternion.Euler(0f, transform.localRotation.eulerAngles.y + mouseX, 0f);
    41.         Camera.main.transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f);
    42.     }
    43.  
    44. }
     
  11. kader1081

    kader1081

    Joined:
    Oct 16, 2021
    Posts:
    406
    i dont think this is possible
    because error is in line 45 but there is no line 45

    "at Assets/Scripts/movement.cs:45"
     
  12. kader1081

    kader1081

    Joined:
    Oct 16, 2021
    Posts:
    406
    i believe problem is in inputField.GetComponent<Text>().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
     
  13. Ryiah

    Ryiah

    Joined:
    Oct 11, 2012
    Posts:
    21,937
    Check that you have a camera with the
    MainCamera
    tag.
     
  14. wonderfulsandy

    wonderfulsandy

    Joined:
    Mar 1, 2024
    Posts:
    2
    thank you so much for your effort, it was the tag indeed, much appreciated.