Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Voting for the Unity Awards are OPEN! We’re looking to celebrate creators across games, industry, film, and many more categories. Cast your vote now for all categories
    Dismiss Notice
  3. Dismiss Notice

Getting NullReferenceException despite assigning an object

Discussion in 'Editor & General Support' started by weisiantung, Apr 26, 2018.

  1. weisiantung

    weisiantung

    Joined:
    Apr 25, 2018
    Posts:
    2
    I don't understand why am I getting the NullReferenceException error although I have already assigned a gameobject.


    Code (CSharp):
    1. public class PositionSavers : MonoBehaviour
    2. {
    3.     public GameObject tracked;
    4.     private static int n = 0;
    5.     private static Vector3[] objectPositions = null;
    6.  
    7.     private void Start()
    8.     {
    9.     }
    10.  
    11.     private void Update()
    12.     {
    13.         if(n < 500)
    14.         {
    15.             objectPositions[n] = tracked.transform.position;
    16.             n++;
    17.         }
    18.         if(n == 500)
    19.         {
    20.             Save(objectPositions);
    21.             n++;
    22.         }
    23.     }
    24. }
    upload_2018-4-26_5-45-30.png

    upload_2018-4-26_5-46-41.png
     
  2. Prastiwar

    Prastiwar

    Joined:
    Jul 29, 2017
    Posts:
    125
    You get null from there?
    objectPositions[n] = tracked.transform.position;

    Probably yes, your array is null
    private static Vector3[] objectPositions = null;
    . I don't see anywhere in code where you initialize it, so it'd be still null.
     
  3. weisiantung

    weisiantung

    Joined:
    Apr 25, 2018
    Posts:
    2
    Thanks for replying!! I just solved the problem. I am a new learner to this. So sorry for the stupid question.