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. Dismiss Notice

Question NullReferenceException

Discussion in 'Scripting' started by dzvera951, May 29, 2021.

  1. dzvera951

    dzvera951

    Joined:
    Mar 4, 2021
    Posts:
    6
    I have been trying to figure out for hours why this code is coming up with an error, it works but since there is an error it surely can not be working correctly. I would appreciate it so much if someone could help me ;o?

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class SpawnAbilities : MonoBehaviour
    6. {
    7.     public LayerMask collidingLayer;
    8.     public GameObject vfxMarkerPrefab;
    9.     public List<GameObject> VFX;
    10.  
    11.     public Vector3 vfxOffset;
    12.     private bool aiming = false;
    13.     private GameObject vfxMarker;
    14.     private GameObject effectToSpawn;
    15.     private Animator anim;
    16.     private MovementInput movementInput;
    17.     private int currentAttack;
    18.  
    19.  
    20.     // Start is called before the first frame update
    21.     void Start()
    22.     {
    23.         anim = GetComponent<Animator>();
    24.         Cursor.visible = false;
    25.         vfxMarker = Instantiate(vfxMarkerPrefab) as GameObject;
    26.         vfxMarker.SetActive(false);
    27.         if (VFX.Count > 0)
    28.             effectToSpawn = VFX[0];
    29.     }
    30.  
    31.     // Update is called once per frame
    32.     void Update()
    33.     {
    34.         if(Input.GetMouseButtonDown(1))
    35.         {
    36.             aiming = true;
    37.             vfxMarker.SetActive(true);
    38.         }
    39.  
    40.         if(Input.GetMouseButtonUp(1))
    41.         {
    42.             aiming = false;
    43.             vfxMarker.SetActive(false);
    44.         }
    45.  
    46.         if(Input.GetKeyDown(KeyCode.Alpha1))
    47.         {
    48.             VFXSelecter(1);
    49.         }
    50.  
    51.         if(Input.GetMouseButtonDown(2))
    52.         {
    53.             if (aiming)
    54.             {
    55.                 anim.SetTrigger("Attack01");
    56.                 var vfx = Instantiate(effectToSpawn, vfxMarker.transform.position + vfxOffset, Quaternion.identity) as GameObject;
    57.                 Destroy(vfx, 5);
    58.             }
    59.         }
    60.  
    61.  
    62.         if (aiming)
    63.         {
    64.             RaycastHit hit;
    65.             Ray ray = new Ray(Camera.main.transform.position, Camera.main.transform.forward);
    66.  
    67.             if(Physics.Raycast(ray, out hit, Mathf.Infinity, collidingLayer))
    68.             {
    69.                 vfxMarker.SetActive(true);
    70.                 vfxMarker.transform.position = hit.point;
    71.             }
    72.             else
    73.             {
    74.                 vfxMarker.SetActive(false);
    75.             }
    76.         }
    77.     }
    78.  
    79.     void VFXSelecter (int number)
    80.     {
    81.         currentAttack = number;
    82.         if (VFX.Count > number - 1) ;
    83.         {
    84.             effectToSpawn = VFX[number - 1];
    85.         }
    86.     }
    87. }
    88.  
    Code (CSharp):
    1. NullReferenceException: Object reference not set to an instance of an object
    2. SpawnAbilities.Update () (at Assets/GabrielAguiarProductions/Scripts/MarkerAoe/SpawnAbilities.cs:65)
    And a warning
    Code (CSharp):
    1.  Assets\GabrielAguiarProductions\Scripts\MarkerAoe\SpawnAbilities.cs(71,37): warning CS0642: Possible mistaken empty statement.
    I am basically trying to move this Aoe marker to my mouse position but instead Its just staying in the middle of the map https://gyazo.com/497f446647c038bb07ae3891f10c8241
    https://gyazo.com/ff2e7024c23a41811918c48b45265513
     
    Last edited: May 29, 2021
  2. jasonasaad2

    jasonasaad2

    Joined:
    Nov 30, 2020
    Posts:
    51
    You need to make sure all variables are assigned to an object.
    EDIT: try this
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. public class SpawnAbilities : MonoBehaviour
    5. {
    6.     public LayerMask collidingLayer;
    7.     public GameObject vfxMarkerPrefab;
    8.     public List<GameObject> VFX;
    9.     public Vector3 vfxOffset;
    10.     private bool aiming = false;
    11.     private GameObject vfxMarker;
    12.     private GameObject effectToSpawn;
    13.     private Animator anim;
    14.     private MovementInput movementInput;
    15.     private int currentAttack;
    16.     public Camera Camera;
    17.     // Start is called before the first frame update
    18.     void Start()
    19.     {
    20.         anim = GetComponent<Animator>();
    21.         Cursor.visible = false;
    22.         vfxMarker = Instantiate(vfxMarkerPrefab) as GameObject;
    23.         vfxMarker.SetActive(false);
    24.         if (VFX.Count > 0)
    25.             effectToSpawn = VFX[0];
    26.     }
    27.     // Update is called once per frame
    28.     void Update()
    29.     {
    30.         if(Input.GetMouseButtonDown(1))
    31.         {
    32.             aiming = true;
    33.             vfxMarker.SetActive(true);
    34.         }
    35.         if(Input.GetMouseButtonUp(1))
    36.         {
    37.             aiming = false;
    38.             vfxMarker.SetActive(false);
    39.         }
    40.         if(Input.GetKeyDown(KeyCode.Alpha1))
    41.         {
    42.             VFXSelecter(1);
    43.         }
    44.         if(Input.GetMouseButtonDown(2))
    45.         {
    46.             if (aiming)
    47.             {
    48.                 anim.SetTrigger("Attack01");
    49.                 var vfx = Instantiate(effectToSpawn, vfxMarker.transform.position + vfxOffset, Quaternion.identity) as GameObject;
    50.                 Destroy(vfx, 5);
    51.             }
    52.         }
    53.         if (aiming)
    54.         {
    55.             RaycastHit hit;
    56.             Ray ray = new Ray(Camera.main.transform.position, Camera.main.transform.forward);
    57.             if(Physics.Raycast(ray, out hit, Mathf.Infinity, collidingLayer))
    58.             {
    59.                 vfxMarker.SetActive(true);
    60.                 vfxMarker.transform.position = hit.point;
    61.             }
    62.             else
    63.             {
    64.                 vfxMarker.SetActive(false);
    65.             }
    66.         }
    67.     }
    68.     void VFXSelecter (int number)
    69.     {
    70.         currentAttack = number;
    71.         if (VFX.Count > number - 1) ;
    72.         {
    73.             effectToSpawn = VFX[number - 1];
    74.         }
    75.     }
    76. }
     
  3. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,756
    I think you're doing something wrong. Nullref fix time should be measured in seconds, or perhaps minutes.

    Not sure what approach you're using, but there's only one approach that actually works fast every time.

    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
     
  4. dzvera951

    dzvera951

    Joined:
    Mar 4, 2021
    Posts:
    6
    Hey, thanks for trying :) I attempted it but it still didn't work. I'm basically trying to get this Aoe marker to move but instead It's just staying in one place.. https://gyazo.com/497f446647c038bb07ae3891f10c8241

    And it displays this warning message

    Assets\GabrielAguiarProductions\Scripts\MarkerAoe\SpawnAbilities.cs(71,37): warning CS0642: Possible mistaken empty statement.
     
  5. dzvera951

    dzvera951

    Joined:
    Mar 4, 2021
    Posts:
    6

    Thanks! Ill try and but I'm not as advanced.. but Ill attempt it
     
  6. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,756
    It actually doesn't matter with Null Ref. There is only one solution with three steps. All others are a waste of time. You're welcome to try other approaches, as that is your own time wasted.

    Again, the basic steps outlined above are:
    - Identify what is null
    - Identify why it is null
    - Fix that.
     
  7. dzvera951

    dzvera951

    Joined:
    Mar 4, 2021
    Posts:
    6
    Yeh - I never found out how to do it.. to me everything seems fine..
     
  8. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,756
    You're telling me that everything happening on the line it is complaining about:

    Is "fine?" As in "is not null?"

    Because I kinda doubt the computer is pulling your leg.
     
  9. dzvera951

    dzvera951

    Joined:
    Mar 4, 2021
    Posts:
    6
    .-. I do n o t know how to fix it... I have only been starting c# a month ago..

    Could you please do it? and if possible write comments so Ill know how to next time?
     
  10. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,756
    I would love to if I could.

    The problem is there is something fundamentally not complete about your implementation of whatever tutorial it is you have found above and chosen to tinker with.

    Although line 65 does not match exactly in this forum post, it appears that
    vfxMarker
    is null.

    At a minimum in order to function in Unity, you must be able to prove/disprove this yourself, either by attaching the debugger and inspecting the value, or else by using Debug.Log().

    You also must be able to identify where variables are supposed to be initialized in order to reason about why they might not be initialized in this case.

    Looking above,
    vfxMarker
    is initialized (on or around line 22) as a result of Instantiating something that might be a prefab, then casting it to a GameObject.

    So did you at least drag in the prefab that this Instantiates from? That's the first thing to check.

    ALL of those steps must succeed (and the initialization code must be executed, eg. no OTHER errors preventing it from running!) for
    vfxMarker
    to be initialized.

    But I cannot through sheer force of will cause your scene and setup and tutorial to be complete. Only you can do that.

    How to do tutorials properly:

    Tutorials are a GREAT idea. Tutorials should be used this way:

    Step 1. Follow the tutorial and do every single step of the tutorial 100% precisely the way it is shown. Even the slightest deviation generally ends in disaster. That's how software engineering works. Every single letter must be spelled, capitalized, punctuated and spaced (or not spaced) properly. Fortunately this is the easiest part to get right. Be a robot. Don't make any mistakes. BE PERFECT IN EVERYTHING YOU DO HERE.

    Step 2. Go back and work through every part of the tutorial again, and this time explain it to your doggie. See how I am doing that in my avatar picture? If you have no dog, explain it to your house plant. If you are unable to explain any part of it, STOP. DO NOT PROCEED. Now go learn how that part works. Read the documentation on the functions involved. Go back to the tutorial and try to figure out WHY they did that. This is the part that takes a LOT of time when you are new. It might take days or weeks to work through a single 5-minute tutorial. Stick with it. You will learn.

    Step 2 is the part everybody seems to miss. Without Step 2 you are simply a code-typing monkey and outside of the specific tutorial you did, you will be completely lost.

    Of course, all this presupposes no errors in the tutorial. For certain tutorial makers (like Unity, Brackeys, Imphenzia, Sebastian Lague) this is usually the case. For some other less-well-known content creators, this is less true. Read the comments on the video: did anyone have issues like you did? If there's an error, you will NEVER be the first guy to find it.

    Beyond that, Step 3, 4, 5 and 6 become easy because you already understand!
     
    Last edited: May 30, 2021
  11. dzvera951

    dzvera951

    Joined:
    Mar 4, 2021
    Posts:
    6
    Yeh, I tried to follow the tutorial 100% but he kept cutting stuff out. I did track the prefab to the inspection thats the first thing I checked. Yeh someone else had the same Issue I did but the owner never got back to him, someone offered a tweak in code but it didn't work afterall. I appreciate your attempts to help, I redone the tutorial like 3 times.. If I don't end up figuring out Ill probably end up messaging one of the owner's social.
     
  12. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,756
    So you verified that it is filled out?

    Is it possible you put this script on more than one GameObject inadvertently? Put a
    Debug.Log("Start():" + name);
    as the first line in the Start() method, find out!

    There should only be one of those printed. If there's more than one (or however many you expect), find the others and remove them.

    There are a lot of really good tutorials out there. You should work through many (see what "work through" means above) because even if you don't find one that is PRECISELY what you look for, you'll soon be good enough to just make what you want out of whole cloth.

    That is after all the entire point here.