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

Hi guys I need you help I got a bit of a problem with my code. I still dont know which gameobject it is referring to since typeofanims has been declared to copy an enum from another script. Trying to compare two objects by using enum as their types. Thank you in advance =)

 public game3_objectdrop.Slot typeofanims = game3_objectdrop.Slot.chicken;

void OnTriggerEnter(Collider other)
    {
      
       
       
        if ( other.tag == "cube")
        {
          
            game3_objectdrop t = gameObject.GetComponent<game3_objectdrop>();
           
            if (typeofanims == t.typeofAnims)
           {
                Debug.Log("You touch me");
                touchme = true;
                gameObject.transform.position = other.transform.position;
                gameObject.transform.SetParent(other.transform.parent);
          }
            else
           {

               originalPosition = gameObject.transform.position;
          }

          
        }
    }

hello.
Check if gameObject.GetComponent<game3_objectdrop>() != null
other.transform.parent may not have a parent? so it can return null

1 Like

hi thank you so much for replying I removed the .parent on other. It’s still doing it. what im doing is if a drag the object to a certain object so it can copy its position if it has the same type. Am i going to check the null before i check the type?

Hi i did this when dragging the object to the cube and it is getting null

void OnTriggerEnter(Collider other)
    {
    
      
      
        if ( other.tag == "cube")
        {
        
            game3_objectdrop t = gameObject.GetComponent<game3_objectdrop>();
            if (gameObject.GetComponent<game3_objectdrop>() != null)
            {
                if (typeofanims == t.typeofAnims)
                {
                    Debug.Log("You touch me");
                    touchme = true;
                    gameObject.transform.position = other.transform.position;
                    gameObject.transform.SetParent(other.transform);
                }
                else
                {
                    originalPosition = gameObject.transform.position;
                }
            }
            else
            {
                Debug.Log("null");
            }
        
        }
    }

If it say null this mean that the colliding object dont have a game3_objectdrop component

1 Like