Trouble with destroy function

Hi, I am trying to make a cooperative game about two cubes. I am scripting a button to delete or make a door invisible and passable. This script has worked for pressing the button, but as soon as I add a Destroy(other) command it stops working. This is my code:

public bool pressed = (false);
public GameObject other;

void OnTriggerEnter(Collider other)
	if (other.tag == "player2")

The boolean is to check if the button is pressed, which is mostly just for me in the editor. The GameObject is a reference to my door, which I assign in the editor. Keep in mind that both the door and button are prefabs, and I am editing the version in the scene, not the one in the folder. Now, before I added the Destroy(other); command, the script worked fine. The button was pressed and no errors occurred. As soon as I added the Destroy(other); command, the script hasn’t been working and hasn’t changed the colour or pressed or anything. I am coming back from a long break of not programming, so I am a bit sketchy about the trouble.

Switch between the last 2 lines of code. The script is getting deactivated before it can destroy the “other” gameObject.

If the gameObject is not active, then all it’s components (including scripts) are also not active.

Your main problem is probably your “other” variable(s)!!!

You have named one member variable of your script “other” and also the parameter of OnTriggerEnter. Inside OnTriggerEnter when you use “other” you will refer to the collider you hit (which is the collider of the object tagged “player2”). This collider you actually destroy. So you don’t destroy the whole gameobject, just the collider. You might wanted to destroy the gameobject referenced by your member variable “other”.

A classical example of a bad variable name :wink: In case of OnTriggerEnter “other” is a well choosen name since we don’t know what it will be. We could collide with anything. “otherCollider” would probably be better but other is ok. However a member variable called “other” is suspicious. There is this script and “another” so naturally i would expect other to be of the same type as this script, why else would you call it other?

If it should reference the door gameobject, call it “door”. If the script is a more general purpose script, call it “target”.

In case you want to keed your two “other” variables, you can use:


which will use the member variable and not the local variable. However, that’s not recommended. Keep in mind if you rename the member variable you need to reassign it in the inspector.