Search Unity

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

Discussion in 'Scripting' started by Aron95, Jun 22, 2020.

  1. Aron95

    Aron95

    Joined:
    Jun 22, 2020
    Posts:
    3
    Hello People,

    im relativ new to scripting and have startet a tower defensgame. I mark different ojects with different marks like in a RTS. When i mark a Enemy and this Enemy runs to the Endpoint with the mark. The Enemy will get destoryed but the mark still exists and i get this report:

    NullReferenceException: Object reference not set to an instance of an object
    Mark_Controller.Update () (at Assets/Scripts/Marking_Objects/Mark_Controller.cs:27)


    The Line 27 is where i check if the gameobjekt is empty in Mark_Controller in the Update function. I really dont get why this happens.

    I could not us the Ask Forum i got Gatway 504

    Here is my Code for Enemy Controller


    Code (CSharp):
    1.     using UnityEngine;
    2.     using UnityEngine.AI;
    3.     using System.Collections;
    4.     public class Enemy_Controller : MonoBehaviour
    5.     {
    6.  
    7.         public GameObject Endpoint;
    8.         public Enemy Enemy;
    9.  
    10.         private Mark_Controller markController;
    11.         // Start is called before the first frame update
    12.         void Start()
    13.         {
    14.             markController = GetComponent<Mark_Controller>();
    15.             Endpoint = GameObject.FindWithTag("Endpoint");
    16.             Vector3 End = Endpoint.transform.position;
    17.  
    18.             NavMeshAgent agent = GetComponent<NavMeshAgent>();
    19.             agent.destination = End;
    20.          
    21.         }
    22.         private void OnTriggerEnter(Collider other)
    23.         {
    24.          
    25.             if (other.tag == "Endpoint")
    26.             {
    27.                 Destroy(gameObject);  
    28.             }
    29.          
    30.         }
    31.     }
    Here for Mark_Controller
    Code (CSharp):
    1. using UnityEngine;
    2.  
    3.     public class Mark_Controller : MonoBehaviour
    4.     {
    5.         public GameObject mark_green;
    6.         public GameObject mark_red;
    7.         public GameObject mark_yellow;
    8.  
    9.  
    10.         private bool markSet = false;
    11.         private GameObject marks;
    12.  
    13.         private RaycastHit hit;
    14.         private GameObject gameObject;
    15.         private Vector3 relativ = new Vector3(0, 0.5f, 0);
    16.  
    17.  
    18.    
    19.  
    20.         private void Update()
    21.         {
    22.          
    23.             if (markSet == true)
    24.             {
    25.                 if (hit.collider.gameObject == null)
    26.                     unsetMark();
    27.                 else
    28.                 {
    29.                     gameObject = hit.collider.gameObject;
    30.                     Debug.Log(gameObject);
    31.                     if (gameObject != null)
    32.                     {
    33.                         marks = GameObject.FindGameObjectWithTag("Mark");
    34.                         Debug.Log("Mark exist");
    35.                         marks.transform.position = gameObject.transform.position - relativ;
    36.                     }
    37.                     else
    38.                     {
    39.                         Debug.Log("unmark");
    40.                         unsetMark();
    41.                     }
    42.                 }      
    43.             }
    44.             else
    45.                 {
    46.                 unsetMark();
    47.                 }
    48.  
    49.          
    50.         }
    51.  
    52.         public void setMark(RaycastHit hit,Ray ray)
    53.         {
    54.             unsetMark();
    55.             if (hit.collider.GetComponent<Player>() != null && markSet == false)
    56.             {
    57.                 this.hit    = hit;
    58.                 Vector3 pos = GameObject.FindGameObjectWithTag("Player").transform.position;
    59.                 Instantiate(mark_green, pos - relativ, Quaternion.Euler(90, 0, 0));
    60.                 markSet = true;
    61.             }
    62.             else if (hit.collider.GetComponent<Enemy_Controller>() != null && markSet == false)//For Enemy
    63.             {
    64.                 this.hit    = hit;
    65.                 Vector3 pos = hit.transform.position;
    66.                 Instantiate(mark_red, pos - relativ, Quaternion.Euler(90, 0, 0));
    67.                 markSet = true;
    68.             }
    69.             else if (hit.collider.GetComponent<Shop>() != null && markSet == false) //For Shop
    70.             {
    71.                 this.hit    = hit;
    72.                 Vector3 pos = GameObject.FindGameObjectWithTag("Shop").transform.position;
    73.                 Instantiate(mark_yellow, pos - relativ, Quaternion.Euler(90, 0, 0));
    74.                 markSet = true;
    75.             }
    76.         }
    77.         public void unsetMark()
    78.         {
    79.             markSet = false;
    80.             marks = GameObject.FindGameObjectWithTag("Mark");
    81.             Destroy(marks);
    82.         }
    83.  
    84.      
    85.     }
    And here my Raycastshooter


    Code (CSharp):
    1. using UnityEngine;
    2.  
    3.     public class RaycastShooter : MonoBehaviour
    4.     {
    5.  
    6.         private Camera screenCamera;
    7.         private Mark_Controller markController;
    8.         private Mark_UI_Controller markUiController;
    9.      
    10.  
    11.  
    12.         private void Start()
    13.         {
    14.             screenCamera = GetComponent<Camera>();
    15.             markController = GetComponent<Mark_Controller>();
    16.             markUiController = GetComponent<Mark_UI_Controller>();
    17.         }
    18.         // Update is called once per frame
    19.         private void FixedUpdate()
    20.         {
    21.          
    22.             if(Input.GetMouseButtonDown(0))
    23.             {
    24.                 markGameobject();
    25.             }
    26.  
    27.             if(Input.GetMouseButton(1))
    28.             {
    29.                 unmarkGameobject();
    30.             }
    31.     ;    }
    32.  
    33.  
    34.         public void markGameobject()
    35.         {
    36.             Ray ray = screenCamera.ScreenPointToRay(Input.mousePosition);
    37.             RaycastHit hit;
    38.             if(Physics.Raycast(ray, out hit, Mathf.Infinity)) //For Player
    39.             {
    40.                 markController.setMark(hit, ray);
    41.                 markUiController.createUI(hit,ray);
    42.             }
    43.         }
    44.  
    45.         public void unmarkGameobject()
    46.         {
    47.             markController.unsetMark();
    48.             markUiController.uncreateUI();
    49.         }
    50.  
    51.      
    52.     }
    53.  
    Pictures

     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,745
  3. norilalatoli

    norilalatoli

    Joined:
    Aug 9, 2018
    Posts:
    12
    Its because in your Mark_Controller, you never assigned anything to 'hit'. 'hit' is null, so trying to access 'hit.collider' will give you a null reference error.
     
  4. thehappyinthehouse

    thehappyinthehouse

    Joined:
    Jun 23, 2020
    Posts:
    1
    Hi, I'm completely new to C# and all of coding ever. I'm trying to use the Beginner Code creator kit, and in following the instructions, one of the scripts from Unity is producing this error message for line 178. The message and the code is below.

    NullReferenceException: Object reference not set to an instance of an object
    NameWindow.OnGUI () (at Assets/Creator Kit - Beginner Code/Scripts/Editor/CreateScriptEditor.cs:178)

    Code (CSharp):
    1. using System.IO;
    2. using UnityEngine;
    3. using UnityEditor;
    4. using System.CodeDom.Compiler;
    5.  
    6. public class CreateScriptEditor
    7. {
    8.     [MenuItem("Beginner Code/Create Item Effect")]
    9.     static void CreateItemEffect()
    10.     {
    11.         var win = EditorWindow.GetWindow<NameWindow>();
    12.         win.Display();
    13.  
    14.         win.OnValidate = s =>
    15.         {
    16.             string[] asset = AssetDatabase.FindAssets("SampleItemEffect");
    17.  
    18.             if (asset.Length > 0)
    19.             {
    20.                 var textAsset = AssetDatabase.LoadAssetAtPath<TextAsset>(AssetDatabase.GUIDToAssetPath(asset[0]));
    21.  
    22.                 string result = textAsset.text.Replace("{EFFECTNAME}", s);
    23.  
    24.                 string targetPath = Application.dataPath + "/Scripts/ItemEffect/";
    25.                 Directory.CreateDirectory(targetPath);
    26.  
    27.                 targetPath += s + ".cs";
    28.                 File.WriteAllText(targetPath, result);
    29.                 AssetDatabase.Refresh();
    30.  
    31.                 Selection.activeObject = AssetDatabase.LoadMainAssetAtPath(targetPath.Replace(Application.dataPath, "Assets"));
    32.                 EditorWindow.GetWindow(System.Type.GetType("UnityEditor.ProjectBrowser, UnityEditor"));
    33.                 EditorGUIUtility.PingObject(Selection.activeObject);
    34.             }
    35.             else
    36.             {
    37.                 Debug.LogError("Couldn't find the sample item effect script file");
    38.             }
    39.         };
    40.     }
    41.  
    42.     [MenuItem("Beginner Code/Create Weapon Attack Effect")]
    43.     static void CreateWeaponEffect()
    44.     {
    45.         var win = EditorWindow.GetWindow<NameWindow>();
    46.         win.Display();
    47.  
    48.         win.OnValidate = s =>
    49.         {
    50.             string[] asset = AssetDatabase.FindAssets("SampleWeaponEffect");
    51.  
    52.             if (asset.Length > 0)
    53.             {
    54.                 var textAsset = AssetDatabase.LoadAssetAtPath<TextAsset>(AssetDatabase.GUIDToAssetPath(asset[0]));
    55.  
    56.                 string result = textAsset.text.Replace("{EFFECTNAME}", s);
    57.  
    58.                 string targetPath = Application.dataPath + "/Scripts/WeaponEffect/";
    59.                 Directory.CreateDirectory(targetPath);
    60.  
    61.                 targetPath += s + ".cs";
    62.                 File.WriteAllText(targetPath, result);
    63.                 AssetDatabase.Refresh();
    64.                
    65.                 Selection.activeObject = AssetDatabase.LoadMainAssetAtPath(targetPath.Replace(Application.dataPath, "Assets"));
    66.                 EditorWindow.GetWindow(System.Type.GetType("UnityEditor.ProjectBrowser, UnityEditor"));
    67.                 EditorGUIUtility.PingObject(Selection.activeObject);
    68.             }
    69.             else
    70.             {
    71.                 Debug.LogError("Couldn't find the sample weapon effect script file");
    72.             }
    73.         };
    74.     }
    75.    
    76.     [MenuItem("Beginner Code/Create Equipped Effect")]
    77.     static void CreateEquippedEffect()
    78.     {
    79.         var win = EditorWindow.GetWindow<NameWindow>();
    80.         win.Display();
    81.  
    82.         win.OnValidate = s =>
    83.         {
    84.             string[] asset = AssetDatabase.FindAssets("SampleEquipmentEffect");
    85.  
    86.             if (asset.Length > 0)
    87.             {
    88.                 var textAsset = AssetDatabase.LoadAssetAtPath<TextAsset>(AssetDatabase.GUIDToAssetPath(asset[0]));
    89.  
    90.                 string result = textAsset.text.Replace("{EFFECTNAME}", s);
    91.  
    92.                 string targetPath = Application.dataPath + "/Scripts/EquippedEffect/";
    93.                 Directory.CreateDirectory(targetPath);
    94.  
    95.                 targetPath += s + ".cs";
    96.                 File.WriteAllText(targetPath, result);
    97.                 AssetDatabase.Refresh();
    98.                
    99.                 Selection.activeObject = AssetDatabase.LoadMainAssetAtPath(targetPath.Replace(Application.dataPath, "Assets"));
    100.                 EditorWindow.GetWindow(System.Type.GetType("UnityEditor.ProjectBrowser, UnityEditor"));
    101.                 EditorGUIUtility.PingObject(Selection.activeObject);
    102.             }
    103.             else
    104.             {
    105.                 Debug.LogError("Couldn't find the sample equipped effect script file");
    106.             }
    107.         };
    108.     }
    109.    
    110.     [MenuItem("Beginner Code/Create Interactable Object")]
    111.     static void CreateInteractableObject()
    112.     {
    113.         var win = EditorWindow.GetWindow<NameWindow>();
    114.         win.Display();
    115.  
    116.         win.OnValidate = s =>
    117.         {
    118.             string[] asset = AssetDatabase.FindAssets("SampleInteractableObject");
    119.  
    120.             if (asset.Length > 0)
    121.             {
    122.                 var textAsset = AssetDatabase.LoadAssetAtPath<TextAsset>(AssetDatabase.GUIDToAssetPath(asset[0]));
    123.  
    124.                 string result = textAsset.text.Replace("{EFFECTNAME}", s);
    125.  
    126.                 string targetPath = Application.dataPath + "/Scripts/InteractableObjects/";
    127.                 Directory.CreateDirectory(targetPath);
    128.  
    129.                 targetPath += s + ".cs";
    130.                 File.WriteAllText(targetPath, result);
    131.                 AssetDatabase.Refresh();
    132.                
    133.                 Selection.activeObject = AssetDatabase.LoadMainAssetAtPath(targetPath.Replace(Application.dataPath, "Assets"));
    134.                 EditorWindow.GetWindow(System.Type.GetType("UnityEditor.ProjectBrowser, UnityEditor"));
    135.                 EditorGUIUtility.PingObject(Selection.activeObject);
    136.             }
    137.             else
    138.             {
    139.                 Debug.LogError("Couldn't find the sample interactable script file");
    140.             }
    141.         };
    142.     }
    143. }
    144.  
    145. public class NameWindow : EditorWindow
    146. {
    147.     public System.Action<string> OnValidate;
    148.  
    149.     string m_EffectName;
    150.  
    151.     CodeDomProvider _provider;
    152.    
    153.     public void Display()
    154.     {
    155.         var pos = position;
    156.         pos.size = new Vector2(400, 300);
    157.         position = pos;
    158.  
    159.         m_EffectName = "";
    160.  
    161.         if (_provider == null)
    162.             _provider = CodeDomProvider.CreateProvider("CSharp");
    163.        
    164.         ShowModalUtility();
    165.     }
    166.  
    167.     void OnGUI()
    168.     {
    169.         m_EffectName = EditorGUILayout.TextField("Effect Name", m_EffectName);
    170.  
    171.         bool validName = _provider.IsValidIdentifier(m_EffectName);
    172.        
    173.         EditorGUILayout.BeginHorizontal();
    174.  
    175.         GUI.enabled = validName;
    176.         if (GUILayout.Button(validName ? "Create" : "Invalid Name"))
    177.         {
    178.             OnValidate(m_EffectName);
    179.             Close();
    180.         }
    181.  
    182.         GUI.enabled = true;
    183.         if (GUILayout.Button("Cancel"))
    184.         {
    185.             Close();
    186.         }
    187.        
    188.         EditorGUILayout.EndHorizontal();
    189.  
    190.         if (!validName)
    191.         {
    192.             EditorGUILayout.HelpBox("The name is not valid. It shouldn't contains space, start with a number or contains special character like ; or .", MessageType.Error);
    193.         }
    194.     }
    195. }
    I've looked at all the responses on this thread, and also on older threads, but I just don't know enough about coding or C# to know how to fix it. Can someone tell me what I need to fix to get it to work. Thanks!
     
  5. soumya_alphpi

    soumya_alphpi

    Joined:
    Mar 3, 2021
    Posts:
    6
    Hello People, I am new to unity and C# scripting. I wanted to transit from 2d to VR mode. I have attached the code.
    It works but I am getting a Null reference exception in line no -30 and 61.
    I can't figure it out please help me. Here is the code
    /// <summary>
    /// Turns VR mode on and off.
    /// </summary>
    public class VrModeController: MonoBehaviour
    {
    /// <summary>
    /// Gets a value indicating whether the screen has been touched this frame.
    /// </summary>
    private bool _isScreenTouched
    {
    get
    {
    return Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began;
    }
    }
    /// <summary>
    /// Gets a value indicating whether the VR mode is enabled.
    /// </summary>
    private bool _isVrModeEnabled
    {
    get
    {
    return XRGeneralSettings.Instance.Manager.isInitializationComplete;
    }
    }
    /// <summary>
    /// Start is called before the first frame update.
    /// </summary>
    public void Start()
    {
    // Configures the app to not shut down the screen and sets the brightness to maximum.
    // Brightness control is expected to work only in iOS, see:
    // https://docs.unity3d.com/ScriptReference/Screen-brightness.html.
    Screen.sleepTimeout = SleepTimeout.NeverSleep;
    Screen.brightness = 1.0f;
    // Checks if the device parameters are stored and scans them if not.
    // This is only required if the XR plugin is initialized on startup,
    // otherwise these API calls can be removed and just be used when the XR
    // plugin is started.
    if (!Api.HasDeviceParams())
    {
    Api.ScanDeviceParams();
    }
    }
    /// <summary>
    /// Update is called once per frame.
    /// </summary>
    public void Update()
    {
    Screen.orientation = ScreenOrientation.LandscapeLeft;
    if (_isVrModeEnabled)
    {
    if (Api.IsCloseButtonPressed)
    {
    ExitVR();
    }
    if (Api.IsGearButtonPressed)
    {
    Api.ScanDeviceParams();
    }
    Api.UpdateScreenParams();
    }
    else
    {
    if (Screen.orientation == ScreenOrientation.LandscapeLeft)
    {
    EnterVR();
    }
    }
    }
    /// <summary>
    /// Enters VR mode.
    /// </summary>
    private void EnterVR()
    {
    StartCoroutine(StartXR());
    if (Api.HasNewDeviceParams())
    {
    Api.ReloadDeviceParams();
    }
    }
    /// <summary>
    /// Exits VR mode.
    /// </summary>
    private void ExitVR()
    {
    StopXR();
    }
    /// <summary>
    /// Initializes and starts the Cardboard XR plugin.
    /// See https://docs.unity3d.com/Packages/com.unity.xr.management@3.2/manual/index.html.
    /// </summary>
    ///
    /// <returns>
    /// Returns result value of <c>InitializeLoader</c> method from the XR General Settings Manager.
    /// </returns>
    private IEnumerator StartXR()
    {
    Debug.Log("Initializing XR...");
    yield return XRGeneralSettings.Instance.Manager.InitializeLoader();
    if (XRGeneralSettings.Instance.Manager.activeLoader == null)
    {
    Debug.LogError("Initializing XR Failed.");
    }
    else
    {
    Debug.Log("XR initialized.");
    Debug.Log("Starting XR...");
    XRGeneralSettings.Instance.Manager.StartSubsystems();
    Debug.Log("XR started.");
    }
    }
    /// <summary>
    /// Stops and deinitializes the Cardboard XR plugin.
    /// See https://docs.unity3d.com/Packages/com.unity.xr.management@3.2/manual/index.html.
    /// </summary>
    private void StopXR()
    {
    Debug.Log("Stopping XR...");
    XRGeneralSettings.Instance.Manager.StopSubsystems();
    Debug.Log("XR stopped.");
    Debug.Log("Deinitializing XR...");
    XRGeneralSettings.Instance.Manager.DeinitializeLoader();
    Debug.Log("XR deinitialized.");
    }
    }
     
  6. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,745
    Please don't respond to unrelated old threads. It is against forum rules. Instead, make your own new post. It's free.

    For null reference you do NOT need to make a post. You can solve it yourself.

    The answer 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.

    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
     
    QuixStars likes this.