How to slove this error?(Object reference not set to an instance of an object)

I want to make collision work. So I wrote this functuon in a class

void OnTriggerEnter(Collider OtherObject)
{
  if(OtherObject.tag=="GloomingWater")
  {
    Set TampGO=(Set)OtherObject.gameObject.GetComponent("Set");
    TampGO.SetActive();
  }
}

And I wrote another function in class Set

public void Set()
{   
   ActiveOrNot= true;       
}

But I don't know why, when collision happened, it shows this error:"Object reference not set to an instance of an object"

Could anyone help me please!

1 Answer

1

And I wrote another function in class Set

public void Set()
{   
    ActiveOrNot= true;       
}

I highly doubt that. It's invalid. You'd get another error:

`error CS0542: 'Set.Set()': member names cannot be the same as their enclosing type`


However, try out this script. Chances are you're colliding with something that doesn't have a Set component on itself. If this happens, check the log for the output.

void OnTriggerEnter(Collider OtherObject)
{
    if(OtherObject.tag == "GloomingWater")
    {
        Set TampGO = OtherObject.GetComponent<Set>();
        if (TampGO) 
            TampGO.SetActive();
        else
            Debug.Warning("Trying to access non-existing component 'Set' from " + name, OtherObject);
    }
}

If you expect every GloomingWater to have a Set component, you can add it if it doesn't exist.

void OnTriggerEnter(Collider o)
{
    GameObject g = o.gameObject;
    if (g.tag == "GloomingWater")
    {
        Set s = g.GetComponent<Set>() ?? g.AddComponent<Set>();
        s.SetActive();
    }
}

"Chances are you're colliding with something that doesn't have a Set component on itself." Non-existing component -- it doesn't exist! You're assuming there's a Set component on it, but obviously it is missing. Did you place one to start with? Add a Set component to every game object with the tag "GloomingWater" and you should be ok.

–

To give an analogy, you can't grab a fork from a table if the table doesn't have a fork. (Unless you're a magician, but I think we're programmers. We can create a fork on the table if it doesn't exist using our programming powers Set TampGO = OtherObject.GetComponent<Set>(); ?? OtherObject.gameObject.AddComponent<Set>();)

–

You could just do: otherObject.gameObject.active = true;

–

or: otherObject.SendMessage("SetActive", SendMessageOptions.DontRequireReceiver);

–