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

Object reference not set to an instance of an object

Discussion in 'Scripting' started by sobek, Aug 15, 2016.

  1. sobek

    sobek

    Joined:
    Jul 29, 2012
    Posts:
    44
    Hi,

    Got this "classic" error message in the console. Usually this means that unity cant find whatever object you told it to look for cause you perhaps misspelled something. There is a lot of answear to similiar questions but nothing that solves this weird one.

    Okay. So my player has a jetpack particle effect which appears under his feets when the boost-ability is activated.
    LeftFootParticles & RightFootParticles are visible in the inspector where I drag-droped each particle object within them.
    Everything is working great, but I still keep getting the following error for every frame:

    NullReferenceException: Object reference not set to an instance of an object
    EntityBoosterExecutor.FixedUpdate () (at Assets/PlatformerProject/Scripts/EntityBoosterExecutor.cs:46)


    So why do I get errors that the two particle objects within 'LeftFootParticles' & 'RightFootParticles' are not found when they obviously are? cause they actually do get activated/deactiavted as expected.

    Code (CSharp):
    1. using UnityEngine;
    2.  
    3. public class EntityBoosterExecutor : MonoBehaviour
    4. {
    5.     private EntityState state;
    6.     private Rigidbody2D body;
    7.     private EntityStats moveStats;
    8.     [SerializeField] GameObject LeftFootParticles;
    9.     [SerializeField] GameObject RightFootParticles;
    10.  
    11.     void Start()
    12.     {
    13.  
    14.         state = GetComponent<EntityState>();
    15.         moveStats = GetComponent<EntityStats>();
    16.         body = GetComponent<Rigidbody2D>();
    17.  
    18.         RightFootParticles.SetActive(false);
    19.         LeftFootParticles.SetActive(false);
    20.  
    21.     }
    22.  
    23.     void FixedUpdate()
    24.     {
    25.         if (state.isUsingBooster && body.velocity.y < moveStats.maxUpSpeed)
    26.         {
    27.             body.AddForce(Vector3.up * moveStats.boosterUpForce);
    28.          
    29.             if (LeftFootParticles.activeInHierarchy == false){
    30.                 RightFootParticles.SetActive(true);
    31.                 LeftFootParticles.SetActive(true);
    32.             }              
    33.  
    34.         } else if (state.isUsingBooster == false){
    35.             RightFootParticles.SetActive(false);
    36.             LeftFootParticles.SetActive(false);
    37.  
    38.         }
    39.     }
    40. }
     
  2. DanHedges

    DanHedges

    Joined:
    Jan 21, 2016
    Posts:
    77
    Your code does not seem to be complete, the error message says it is failing on line 46... but there is no line 46 in the pasted code. Are you sure it is the particles that it cant find? You are also getting state and moveStats in your start function but not using them until fixed update.

    It would be handy to see which line it is actually failing on to be able to give a better answer.
     
  3. LeftyRighty

    LeftyRighty

    Joined:
    Nov 2, 2012
    Posts:
    5,148
    thats fairly normal for setting up the internal references to other components on the gameobject.

    yup, this :)
     
  4. DanHedges

    DanHedges

    Joined:
    Jan 21, 2016
    Posts:
    77
    Sorry, I don't think I was very clear. I was more wondering if the right and left foot particles were being set correctly within the Start method and the OP was thinking that they were changing state correctly as they are set to inactive in there but something else was failing in the fixed update. For example if moveStats was null then SetActive on the FootParticles would work in the start method but being as nothing is called on the moveStats reference you would not know it was null until fixed update was run (I am not sure if that is any clearer! :) ).

    But it is all a bit of a guess without knowing what is actually failing.
     
    LeftyRighty likes this.
  5. sobek

    sobek

    Joined:
    Jul 29, 2012
    Posts:
    44
    Thank you.
    The reason there is no line 46 is because i removed all comments in order to make the code easier to read.
    This is the full code:

    Code (CSharp):
    1. using UnityEngine;
    2.  
    3.  
    4. public class EntityBoosterExecutor : MonoBehaviour
    5. {
    6.  
    7.     private EntityState state;
    8.     private Rigidbody2D body;
    9.     private EntityStats moveStats;
    10.     [SerializeField] GameObject LeftFootParticles;
    11.     [SerializeField] GameObject RightFootParticles;
    12.  
    13.     void Start()
    14.     {
    15.  
    16.         state = GetComponent<EntityState>();
    17.         moveStats = GetComponent<EntityStats>();
    18.         body = GetComponent<Rigidbody2D>();
    19.  
    20.         RightFootParticles.SetActive(false);
    21.         LeftFootParticles.SetActive(false);
    22.  
    23.     }
    24.  
    25.     void FixedUpdate()
    26.     {
    27.         if (state.isUsingBooster && body.velocity.y < moveStats.maxUpSpeed)
    28.         {
    29.             body.AddForce(Vector3.up * moveStats.boosterUpForce);
    30.             /*
    31.             if(!RightFootParticles == null){
    32.                 RightFootParticles.SetActive(true);
    33.             }
    34.             if(!LeftFootParticles == null){
    35.                 LeftFootParticles.SetActive(true);
    36.             }*/
    37.             if (LeftFootParticles.activeInHierarchy == false){
    38.                 RightFootParticles.SetActive(true);
    39.                 LeftFootParticles.SetActive(true);
    40.             }
    41.            
    42.  
    43.         } else
    44.  
    45.         if (state.isUsingBooster == false){
    46.             RightFootParticles.SetActive(false);
    47.             LeftFootParticles.SetActive(false);
    48.  
    49.         }
    50.  
    51.  
    52.         /*else {
    53.        
    54.             if(!RightFootParticles == null){
    55.                 RightFootParticles.SetActive(false);
    56.             }
    57.             if(!LeftFootParticles == null){
    58.                 LeftFootParticles.SetActive(false);
    59.             }
    60.  
    61.  
    62.         }*/
    63.     }
    64. }
    This is the first error:
    NullReferenceException: Object reference not set to an instance of an object
    EntityBoosterExecutor.Start () (at Assets/PlatformerProject/Scripts/EntityBoosterExecutor.cs:20)

    This is the 2nd error which repets by the loop:
    NullReferenceException: Object reference not set to an instance of an object
    EntityBoosterExecutor.FixedUpdate () (at Assets/PlatformerProject/Scripts/EntityBoosterExecutor.cs:46)

    This is the 3rd error, ehich appears when I press the key to activate the ability:
    NullReferenceException: Object reference not set to an instance of an object
    EntityBoosterExecutor.FixedUpdate () (at Assets/PlatformerProject/Scripts/EntityBoosterExecutor.cs:37)
     
    Last edited: Aug 16, 2016
  6. DanHedges

    DanHedges

    Joined:
    Jan 21, 2016
    Posts:
    77
    From that we can determine that LeftFootParticles and RightFootParticles are null, which makes sense as they are not set anywhere in your code. Being as they have no access modifier then they will be private by default so they are not being set via the editor or anything. You may need a getcomponent call or something to set them up.

    And I know it is commented out, but this will never work :)

    Code (CSharp):
    1.          
    2.   if(!RightFootParticles == null){
    3.                 RightFootParticles.SetActive(false);
    4.             }
    5.             if(!LeftFootParticles == null){
    6.                 LeftFootParticles.SetActive(false);
    7.             }
    8.  
     
  7. blakeordway

    blakeordway

    Joined:
    Aug 9, 2016
    Posts:
    19
    In the Start() function you need to declare what the RightFootParticles and LeftFootParticles are instances of. You are just creating null GameObjects, and then trying to declare them as active or inactive.

    Code (CSharp):
    1.  
    2. state = GetComponent<EntityState>()
    3. moveStats = GetComponent<EntityStats>();
    4. body = GetComponent<Rigidbody2D>();
    5. RightFootParticles=transform.Find("RightFootParticles").gameObject;
    6. LeftFootParticles = transform.Find("LeftFootParticles").gameObject;
    7.  
    8. RightFootParticles.SetActive(false);
    9. LeftFootParticles.SetActive(false);
    10.  
    I believe that should fix the problem with them being null
     
  8. Dekata

    Dekata

    Joined:
    May 20, 2016
    Posts:
    47
    Guys, I have a same problem,error at line 93, but i dont know where is the mistake :(
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3. using System.Collections.Generic;
    4. using System;
    5.  
    6. public class UserInput : MonoBehaviour {
    7.  
    8.     public CharacterMovementSwat characterMove { get; protected set; }
    9.     public WeaponHandle weaponHandle { get; protected set; }
    10.     [System.Serializable]
    11.     public class OtherSetting
    12.     {
    13.         public float lookSpeed = 5.0f;
    14.         public float lookDistance = 10f;
    15.         public bool requierInputForTurn = true;
    16.         public LayerMask aimDetectionLayer;
    17.     }
    18.     [SerializeField]
    19.     public OtherSetting other;
    20.     public bool debugAim;
    21.     public Transform spine;
    22.     bool aiming;
    23.     Camera mainCam;
    24.     // Use this for initialization
    25.  
    26.     // Update is called once per frame
    27.     void Update () {
    28.      
    29.         WeaponLogic();
    30.     }
    31.     void WeaponLogic()
    32.     {
    33.         if (Input.GetButtonDown("SwitchWeapon"))
    34.         {
    35.             Debug.Log(weaponHandle.currentWeapon.name);
    36.             weaponHandle.SwitchWeapon();  // Here is the error
    37.         }
    38.     }
    39. }
    40.  
    and this is where SwitchWeapon() is
    Code (CSharp):
    1.  
    2. public class WeaponHandle : MonoBehaviour {
    3.  
    4.     [System.Serializable] public class UserSettings
    5.     {
    6.         public Transform rightHand;
    7.         public Transform pistolUnequipSpot;
    8.         public Transform rifleUnequipSpot;
    9.     }
    10.     [SerializeField]
    11.     public UserSettings userSets;
    12.  
    13.     public Weapon currentWeapon;
    14.     public List<Weapon> weaponList = new List<Weapon>();
    15.     public int maxWeapon = 2;
    16.     bool setWeaponbool;
    17.  
    18.     void OnEnable()
    19.     {
    20.         SetupWeapon();
    21.     }
    22.  
    23.     void SetupWeapon()
    24.     {
    25.        if (currentWeapon)
    26.         {
    27.             currentWeapon.SetEquipped(true);
    28.             currentWeapon.SetOwner(this);
    29.             AddWeaponToList(currentWeapon);
    30.         }
    31.  
    32.        if (weaponList.Count > 0)
    33.         {
    34.             for (int i = 0; i < weaponList.Count; i++)
    35.             {
    36.                 if (weaponList[i] != currentWeapon)
    37.                 {
    38.                     weaponList[i].SetEquipped(false);
    39.                     weaponList[i].SetOwner(this);
    40.                 }
    41.             }
    42.         }
    43.     }
    44.  
    45.     void AddWeaponToList(Weapon weapon_)
    46.     {
    47.         if (weaponList.Contains(weapon_)) { return; }
    48.         weaponList.Add(weapon_);
    49.     }
    50.  
    51.     public void SwitchWeapon()
    52.     {
    53.         if (weaponList.Count == 0 || setWeaponbool)
    54.             return;
    55.         if (currentWeapon)
    56.         {
    57.             int currentWeaponIndex = weaponList.IndexOf(currentWeapon);
    58.             int nextWeaponIndex = (currentWeaponIndex + 1) % weaponList.Count;
    59.             currentWeapon = weaponList[nextWeaponIndex];
    60.         }
    61.         else
    62.         {
    63.             currentWeapon = weaponList[0];
    64.         }
    65.  
    66.         setWeaponbool = true;
    67.  
    68.         StartCoroutine(StopSettingWeapon());
    69.  
    70.         SetupWeapon();
    71.     }
    72.  
    73.     IEnumerator StopSettingWeapon()
    74.     {
    75.         yield return new WaitForSeconds(0.7f);
    76.         setWeaponbool = false;
    77.     }
    78. }
    79.  
    I got 2 weapon attached with player but cant swtich them,
    thanks for your help :(
     
    Last edited: Aug 19, 2016
  9. Timelog

    Timelog

    Joined:
    Nov 22, 2014
    Posts:
    528
    He used the [SerializeField] attribute so the fields will show up in the inspector. So that means he doesn't have the objects set up in the inspector (drag the particle object/prefab onto the field in the inspector).

    You don't set weaponHandle anywhere. Also, don't hijack threads.
     
  10. DanHedges

    DanHedges

    Joined:
    Jan 21, 2016
    Posts:
    77
    My bad, so it does :)
     
  11. Dekata

    Dekata

    Joined:
    May 20, 2016
    Posts:
    47
    thanks guys alot, this is the first time i post a question here, and sorry about that mess
     
  12. sobek

    sobek

    Joined:
    Jul 29, 2012
    Posts:
    44
    Thanks for your replies.

    Your code above (using the objects real names which are "Boost Particles L Foot" and "Boost Particles L Foot") gives me the following errors:
    NullReferenceException: Object reference not set to an instance of an object
    EntityBoosterExecutor.Start () (at Assets/PlatformerKit/Scripts/EntityBoosterExecutor.cs:25)


    Yes, I know that I must drag-drop each object to the serialized field in the inspector, as well as I could also make the variabel global to be able to drag-drop a gameobject to the inspector. In the description with my code at the top I wrote:
    So in other words: I have already done that. The whole reason I am using the inspector is becuase I dont want to make a new instance of each object, I just want to use the two objects I already have in the scene.
    But the weird thing/the problem is that I have drag-droped the objects to the inspector and when I run the game unity keep telling me that the two objects are null, which for me makes no sence as I am able to deactivate/activate the objects, which would not be possibvle if they where null.
    So while the game is running everything is working, but I still get error messages.

    Perhaps its a bug?
     
  13. lloydsummers

    lloydsummers

    Joined:
    May 17, 2013
    Posts:
    343
    This is what breakpoints are good for... Just walk the code and find out why the reference is empty.

    If you set the references via editor, clear them, and set them again. It bugs out sometimes. But breakpoints and hovering over objects to see what's up, it's a good way to fix these quickly.

    It isn't saying the object is null. It is saying the specific reference element is null. So either they were destroyed and recreated or something messed with the reference.
     
    Last edited: Aug 21, 2016
  14. blakeordway

    blakeordway

    Joined:
    Aug 9, 2016
    Posts:
    19
    I believe that what I told you earlier was incorrect. Try using 'GameObject.Find()' instead of 'transform.Find()' that should work better;