If I use setActive(true) on a gameObject unity will call: onEnable. But when I am using setActive(false) on the same gameObject Unity would not call onDisable.
The reference says that onEnable is called when the OBJECT becomes enabled and active. OnDisable is called when the BEHAVIOUR becomes disabled () or inactive.
Is there any other callback that is called when setActive(false) on a gameObject is used?
You could make a function that disables the gameobject instead of you gameobject.SetActive(false). Just call your function on your gameobject when you need to destroy it.
public class ObjectClass
{
public void DeactivateObject()
{
// do stuff
gameobject.SetActive(false);
}
}
public class OtherClass
{
void Update()
{
if(hp < 0)
{
gameobject.GetComponent<ObjectClass>().DeactivateObject();
}
}
}
No problem with OnDisable getting called here when SetActive(false) is used. OnEnable and OnDisable work on the same principle; the use of “object” and “behavior” is interchangeable.
–Eric
1 Like
I can’t reproduce the problem. This script deactivates the object and OnDisable gets called automatically.
using System.Collections;
using UnityEngine;
public class Test : MonoBehaviour
{
private void Start()
{
StartCoroutine(DeactivateIn3Seconds());
}
private IEnumerator DeactivateIn3Seconds()
{
yield return new WaitForSeconds(3);
gameObject.SetActive(false);
}
private void OnEnable()
{
Debug.Log("OnEnable");
}
private void OnDisable()
{
Debug.Log("OnDisable");
}
}
Sorry guys, my fault. I used onDisable not OnDisable (Uppercase). In my C++ past methods started with lowercase :).
Thanks for your hints!
1 Like