I am having an issue. I would like a GameObject to disappear after a few seconds after it is activated in my scene. I am able to do that with the script below, but I also want it to be able to work multiple times. Right now it works, but if the object is set to Active a second time in the scene, it does not disappear. I was thinking I could use an if statement to declare "if (gameObject.activeInHierarchy == true), but I am unable to get the actual code block to work properly.
using UnityEngine;
using System.Collections;
public class DestroyObj : MonoBehaviour {
public GameObject gameObject;
void Start (){
// If statement somewhere in here?
StartCoroutine(RemoveAfterSeconds(2, gameObject));
}
IEnumerator RemoveAfterSeconds (int seconds, GameObject obj){
yield return new WaitForSeconds(2);
obj.SetActive(false);
}
}
Any help with this issue would be greatly appreciated. I am also very new to Unity and C#, so if you could be as specific as possible, I would appreciate that as well.
Your if statement is unnecessary. Because it’s being called in OnEnable you can assume that it’s active (otherwise OnEnable wouldn’t fire in the first place).
You also don’t need to pass gameObject into the Coroutine. Just use gameObject.SetActive(false);
Edit: I see what you’re doing. OnEnable is when the GameObject with that script is enabled. Looks like you’re trying to assign some other GameObject to it, which won’t work.
I see, thanks for explaining. I’m still fumbling around with C# a lot, so sometimes I make poor desicions. Can you show me an example of the code to illustrate your point? I’m not sure how to call the GameObject that has the script applied to it.
Not working on a build is a problem not related to the script. It can be hard to find. If I remember right when it happened to me, it was because I had a javascript and a c# script with the same name. It’s pretty vague and it might not even have been that. Look for any warnings in the console and probably do a search.
Having bigger issues now… I installed the new patch and now I’m getting an error that I can’t seem to get rid of. Even tried reverting back to an older patch. Uninstalling the player, reinstalling from an older version and the error still won’t go away. I hope I’m not screwed here. :(