Search Unity

Question Object reference unassigning itself at runtime

Discussion in 'Scripting' started by Wildman537oo, May 7, 2023.

  1. Wildman537oo

    Wildman537oo

    Joined:
    Oct 21, 2019
    Posts:
    3
    I'm trying to reference the grid object which contains a script that has my inventorygrid class. I'm referencing from another script attached to the ui camera.
    upload_2023-5-7_6-2-31.png
    Its assigned like this:
    upload_2023-5-7_6-2-53.png

    I'm just trying to reference it like this:

    Code (CSharp):
    1. public class InventoryController : MonoBehaviour
    2. {
    3.     [SerializeField] private InventoryGrid selectedInventoryGrid;
    4.  
    5.     private void Update()
    6.     {
    7.         if (selectedInventoryGrid = null)
    8.         {
    9.             Debug.Log("InventoryGrid IS null.");
    10.             return;
    11.         }
    12.  
    13.  
    14.         selectedInventoryGrid.GetTileGridPosition(Input.mousePosition);
    15.     }
    16. }
    However, when trying to run the referenced class and method, I get "Object reference not set to an instance of an object.". I've noticed that the "Selected Inventory Grid" that I've assigned just unassigns itself when I run the game.
     
  2. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,914
    In C# = is used to assign things and == is used to compare.

    Here you are assigning it to null.
     
    Bunny83 likes this.
  3. MorpheusZG

    MorpheusZG

    Joined:
    Jan 6, 2020
    Posts:
    18
    selectedInventoryGrid = null

    should be

    selectedInventoryGrid == null
     
    Bunny83 likes this.