So I thought it might be usefull to create a standard script that sets game objects inactive after being spawned, here is what I made real quick
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class turnOff : MonoBehaviour {
public GameObject self;
public int time;
IEnumerator Start()
{
yield return new WaitForSeconds (time);
self.SetActive (false);
}
}
However the problem is, this script somehow only works once. if the object is set to inactive using this script, and then set active again this script won’t say ‘‘ey dude how did you get active again, go back to inactive, quick!’’ like it should. Instead, the objects stays active forever.
What could be wrong here? and no, I do not want the object to be completely destroyed.
The script is attached to the object that gets inactive itself, but since it does get active again later on this shouldnt be a problem too
Yes, that’s the reason. You just work with it, like maybe this:
void OnEnable() {
StartCoroutine(selfHide());
}
IEnumerator SeflHide() {
yield return new WaitForSeconds(hide);
gameObject.setActive(false); // referencing 'self' as a local variable is probably not needed, but not wrong, either.
}
I did a local variable since I want to make this script usable in many instances, so say, if I ever need to disable an object that actually is not itself, I can still use this script, thats why
I stuck with this script and it worked! Thanks for the help everyone!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class turnOff : MonoBehaviour {
public GameObject self;
public int time;
void OnEnable()
{
StartCoroutine (Hide ());
}
IEnumerator Hide()
{
yield return new WaitForSeconds (time);
self.SetActive (false);
}
}
That’s a different story. I would probably have made an own thread for it instead of necoing this one, or looked up one of the other threads about it. Anyways, since an object that is disabled cannot execute scripts, some other script needs to handle the activation. The rest of the idea is basically identical.