Triggering OnTriggerExit() When Object is Destroyed

Hello.

I am writing a game that has a basic button concept. I have a “Marble” object, and a “Button” object. When the Marble touches the Button, I’d like a variable to be set to true.

Here is my script:

public class ActivateButton : MonoBehaviour {

	public bool isActivated = false;

	void OnTriggerEnter (Collider col) {

		if (col.tag == "Marble") isActivated = true;
	
	}

	void OnTriggerExit (Collider col) {
		
		if (col.tag == "Marble") isActivated = false;
		
	}
}

It works fine for simple collisions. However, sometimes my Marble object is destroyed (using Destroy()). This does not call the OnTriggerExit function.

Is there a way to “Destroy” my Marble object in a way that it will call this function? Or is there a way to check for a Destroy() call on a colliding object? Or is there some other way I should be checking for collisions?

I’ve been stuck on this for a while now, and I would really appreciate it if someone could help me.

Thank you,

  • Josh

Hi,

you could add your button to a variable of your marble object. Now if you destroy your marble object you could first call SetActive(false) on the button variable and than destroy the marble object. For that use your own destroy method.

e.g.:


public class ActivateButton : MonoBehaviour {
	
	public bool isActivated = false;
	
	void OnTriggerEnter (Collider col) {
		
		if (col.tag == "Marble")
		{
			isActivated = true;
			col.gameObject.GetComponent<MarbleBehaviour>().AddActivateButton(gameObject);
		}
		
	}
	
	void OnTriggerExit (Collider col) {
		
		if (col.tag == "Marble") isActivated = false;
		
	}	
}

Add this script to your Marble GameObject.

public class MarbleBehaviour : MonoBehaviour {
	
	GameObject button;

	public void AddActivateButton(GameObject obj)
	{
		button = obj;
	}

	void DestroyMarble()
	{
		button.SetActive(false);
		Destroy(gameObject);
	}
}

If someone has same problem, but with just simple game objects set position to something far away - OnTriggerExit() will be fired then

Hi, i had similar problem.
Solved with this unique script:

public class DetectScript : MonoBehaviour {

	public GameObject Tarjet;
    private GameObject triggerObj;

	void Update () {
        // I put here the function that i would call with OnTriggerExit()
	    if (triggerObj != null)
        {
            if (!inTriggerObj.active)
            {
                triggerObj.GetComponent<TriggerObjScript>().DoExitFunct();            
            }
        }
	}

	void OnTriggerStay (Collider other)
    {
		triggerObj.GetComponent<TriggerObjScript>().DoStartFunct();            
        inTriggerObj = other.gameObject;
	}

    void OnTriggerExit (Collider other)
    {
        triggerObj.GetComponent<TriggerObjScript>().DoExitFunct();            
    }
}