- Home /
OnEnable() is not called when SetActive(true)
Hey! I want to make a simple jump and run game where different sets of obstacles are generated again and again so that it never Ends. I tried to do this by activating and deactivating the objects with the SetActive() method (and then changing their Position when they are activated again). The Problem is, that OnEnable() isn't called when the object is activated. Does anyone know why this happens or another way to do this? Thank you!!!
Did you test it with debug.log? Try disabling the script component and enabling it as well.
Answer by Grimm9186 · Feb 24, 2019 at 05:13 PM
Since the script itself wasn't turned off OnEnable() wouldn't be called, if you really want the script to be re-enabled, deactivate it with script.enabled = false;
This will also trigger the OnDisabled() function, then just reanable it after you turned the gameobject back on with script.enabled = true;
This will run OnEnable() again.
i realize now that turning the gameobject off and on should also disable and re-enable the scripts :/. Are you sure you turning the gameobject the Script is attached too off? If so that is quite weird.
Yeah I thought the same thing. The unity documentation says that SetActive(false) turns off the script and the deactivating works(I tested it with the debug.log). But I tried out disabling and enabling the script as well and now it works :) Thank you!!!
Well thats not correct. GameObject.SetActive(state) will call OnEnable() and OnDisable() on every active script attached to the GameObject. See also documentation: https://docs.unity3d.com/ScriptReference/GameObject.SetActive.html
Use script EnableDisableTest on GameObject 01 in the scene:
using UnityEngine;
public class EnableDisableTest : $$anonymous$$onoBehaviour
{
public bool state;
public GameObject objectToTest;
private bool previousState;
public void Start()
{
state = objectToTest.activeInHierarchy;
previousState = state;
}
public void Update()
{
if (state != previousState)
{
objectToTest.SetActive(state);
previousState = state;
}
}
}
And script OrderOfFunctionsTest on GameObject 02 in the scene:
using UnityEngine;
public class OrderOfFunctionsTest : $$anonymous$$onoBehaviour
{
public void Awake()
{
Debug.Log("Order test Awake()");
}
public void OnEnable()
{
Debug.Log("Order test OnEnable()");
}
public void OnDisable()
{
Debug.Log("Order test OnDisable");
}
}
Asign GameObject02 in the inspector to objectToTest of GameObject01. If you start the game, you can use the inspector to toggle state on EnableDisableTest. GameObject02 will toggle between active/inactive and the methodes OnEnable() and OnDisable() will be called accordingly. That also works, if you put OrderOfFunctionsTest on a child GameObject of GameObject02.