Search Unity

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

Discussion in '2D' started by TahaSener07, Nov 3, 2018.

  1. TahaSener07

    TahaSener07

    Joined:
    Oct 12, 2018
    Posts:
    8
    Hello. I'm new to Unity and C#. I get this error when I want my chest to open.
    Here is the code:

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;

    public class Chest : MonoBehaviour {

    public bool playerInRange;
    public GameObject item;
    private Animator animator;

    public void AcilSusamAcil()
    {
    if (playerInRange)
    {
    item.SetActive(true);
    animator.SetBool("isOpen", true);

    }
    }

    private void OnTriggerEnter2D(Collider2D other)
    {
    if (other.gameObject.tag == ("Player"))
    {
    playerInRange = true;
    }

    }

    private void OnTriggerExit2D(Collider2D other)
    {
    if (other.gameObject.tag == ("Player"))
    {
    playerInRange = false;
    }
    }
    }


    This is the error message:
    NullReferenceException: Object reference not set to an instance of an object
    Chest.AcilSusamAcil () (at Assets/Scripts/Chest.cs:16)
    UnityEngine.Events.InvokableCall.Invoke () (at C:/buildslave/unity/build/Runtime/Export/UnityEvent.cs:166)
    UnityEngine.Events.UnityEvent.Invoke () (at C:/buildslave/unity/build/Runtime/Export/UnityEvent_0.cs:58)
    UnityEngine.UI.Button.Press () (at C:/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/UI/Core/Button.cs:36)
    UnityEngine.UI.Button.OnPointerClick (UnityEngine.EventSystems.PointerEventData eventData) (at C:/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/UI/Core/Button.cs:45)
    UnityEngine.EventSystems.ExecuteEvents.Execute (IPointerClickHandler handler, UnityEngine.EventSystems.BaseEventData eventData) (at C:/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/EventSystem/ExecuteEvents.cs:50)
    UnityEngine.EventSystems.ExecuteEvents.Execute[IPointerClickHandler] (UnityEngine.GameObject target, UnityEngine.EventSystems.BaseEventData eventData, UnityEngine.EventSystems.EventFunction`1 functor) (at C:/buildslave/unity/build/Extensions/guisystem/UnityEngine.UI/EventSystem/ExecuteEvents.cs:261)
    UnityEngine.EventSystems.EventSystem:Update()
     
  2. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    11,492
    This tells you what the problem is i.e. on this line you're accessing an object using a NULL reference. This means that the reference, which I believe is either "item" or "animator" isn't set but counting lines as you've posted it it would seem to be the "animator". It is private and I don't see code setting it. You can see it like this (assuming it's on the same GameObject):
    Code (CSharp):
    1. void Start()
    2. {
    3.     animator = GetComponent<Animator>();
    4. }
    I can only presume that "item" is set outside by dragging into that field.

    Note that it's better to use code tags when posting code to make it easier to read and refer to.
     
    MisterSkitz likes this.
  3. TahaSener07

    TahaSener07

    Joined:
    Oct 12, 2018
    Posts:
    8
    WOW! Thank you, that helped me a lot!
     
    MelvMay likes this.
  4. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    11,492
    Anytime, good luck.
     
  5. bunilie

    bunilie

    Joined:
    May 24, 2020
    Posts:
    1
    help me pls, same error...
    public static IEnumerable<Level> GetLevels(GameMode mode)
    {

    return Instance._modeAndLevels[mode];


    }
    on this line....


    and all script

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using UnityEngine;

    public partial class ResourceManager : Singleton<ResourceManager>
    {

    public static event Action<int> CoinsChanged;
    #if IN_APP
    public static event Action<string> ProductPurchased;
    public static event Action<bool> ProductRestored;
    #endif



    public static bool EnableAds
    {
    get => PrefManager.GetBool(nameof(EnableAds), true);
    set => PrefManager.SetBool(nameof(EnableAds), value);
    }

    public static string NoAdsProductId => GameSettings.Default.InAppSetting.removeAdsId;

    public static int Coins
    {
    get => PrefManager.GetInt(nameof(Coins));
    set
    {
    PrefManager.SetInt(nameof(Coins),value);
    CoinsChanged?.Invoke(value);
    }
    }

    protected override void OnInit()
    {
    base.OnInit();
    InitLevels();
    #if IN_APP
    Purchaser = new Purchaser(new List<string>(), new[] { NoAdsProductId });
    Purchaser.RestorePurchased += PurchaserOnRestorePurchased;
    #endif
    }

    #if IN_APP




    public static bool AbleToRestore => EnableAds;

    public Purchaser Purchaser { get; private set; }


    private void PurchaserOnRestorePurchased(bool success)
    {
    if (EnableAds && Purchaser.ItemAlreadyPurchased(NoAdsProductId))
    {
    EnableAds = false;
    ProductPurchased?.Invoke(NoAdsProductId);
    }
    ProductRestored?.Invoke(success);
    }


    public static void RestorePurchase()
    {
    Instance.Purchaser.Restore();
    }

    public static void PurchaseNoAds(Action<bool> completed = null)
    {
    if (!EnableAds)
    {
    return;
    }

    Instance.Purchaser.BuyProduct(NoAdsProductId, success =>
    {
    if (success)
    {
    EnableAds = false;
    }
    completed?.Invoke(success);
    if (success)
    ProductPurchased?.Invoke(NoAdsProductId);
    });
    }
    #endif
    }


    public partial class ResourceManager
    {
    [SerializeField]private List<TextAsset> _modeLvlAssets = new List<TextAsset>();

    private readonly Dictionary<GameMode,List<Level>> _modeAndLevels = new Dictionary<GameMode, List<Level>>();

    private void InitLevels()
    {
    for (var i = 0; i < _modeLvlAssets.Count; i++)
    {
    _modeAndLevels.Add((GameMode)i, JsonUtility.FromJson<LevelGroup>(_modeLvlAssets.text).ToList());
    }
    }

    public static IEnumerable<Level> GetLevels(GameMode mode)
    {

    return Instance._modeAndLevels[mode];


    }

    public static Level GetLevel(GameMode mode,int no)
    {
    if(no>=Instance._modeAndLevels[mode].Count)
    return new Level();
    return Instance._modeAndLevels[mode][no-1];
    }

    public static bool IsLevelLocked(GameMode mode, int no)
    {
    var completedLevel = GetCompletedLevel(mode);

    return no > completedLevel + 1;
    }

    public static int GetCompletedLevel(GameMode mode)
    {
    return PrefManager.GetInt($"{mode}_Level_Complete");
    }

    public static void CompleteLevel(GameMode mode, int lvl)
    {
    if (GetLevel(mode).no>lvl)
    {
    return;
    }

    PrefManager.SetInt($"{mode}_Level_Complete",lvl);
    }

    public static bool HasLevel(GameMode mode, int lvl) => GetLevels(mode).Count() >= lvl;

    public static Level GetLevel(GameMode mode)
    {
    return GetLevel(mode,PrefManager.GetInt($"{mode}_Level_Complete")+1);
    }
    }

    public enum GameMode
    {
    Easy,Normal,Hard
    }
     
  6. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    11,492
    You say you've got the same generic error which doesn't mean it's related to this thread which is years old. You're also hijacking the thread. You should also use code-tags as walls of text are impossible to read. Your post also has nothing to do with 2D features and is just a generic scripting error which should be posted on the scripting forum. Also note you've not even stated which line your error is on; something which is part of the error or if you've tried to debug it etc.

    Thanks.