- Home /
*URGENT* Really Basic Script Problem
Hey Guys, I have an assignment due later today and I have just run into a problem. Basically in my game I have a Gas Can you need to trigger to blow a door. I have done this by pressing 'E'. Afterwards it is supposed to show a series of Canvas' which act like a timer before the explosion. To remove the Canvas' I have used the destroy by time script, and even though the Canvas' are set.active(false) they still are destroyed in my hierarchy when I play. How can I make it so they are only destroyed by time once they are activated? Everything else is working other than this script:
using UnityEngine; using System.Collections; public class DestroyByTime : MonoBehaviour { public float lifetime; void Start() { Destroy(gameObject, lifetime); } }
Answer by Stratosome · Sep 17, 2018 at 01:18 AM
Heyo,
So, the issue is that since all of your canvases are using this script, they all start their destruction timers immediately, right? There are many ways to do this kind of thing, but I'd recommend something like this:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TimedCanvases : MonoBehaviour {
[System.Serializable]
public class TimedCanvas {
public GameObject canvas;
public float lifeTime = 1.0f;
}
public List<TimedCanvas> timedCanvases = new List<TimedCanvas>();
public float gapTime = 0.2f;
void Start () {
// Make sure all canvases are false to begin with
for (int i = 0; i < timedCanvases.Count; i++) {
if (timedCanvases[i].canvas != null) {
timedCanvases[i].canvas.SetActive(false);
}
}
}
// Begins the coroutine which handles the "toggling" of your canvases
public void BeginEvent() {
StartCoroutine(BeginEventCoroutine());
}
private IEnumerator BeginEventCoroutine() {
for (int i = 0; i < timedCanvases.Count; i++) {
if (timedCanvases[i].canvas != null) {
timedCanvases[i].canvas.SetActive(true);
yield return new WaitForSeconds(timedCanvases[i].lifeTime);
Destroy(timedCanvases[i].canvas);
yield return new WaitForSeconds(gapTime);
}
}
}
}
So, with this, you can assign canvases and lifetimes in the inspector, and when you eventually call the public BeginEvent() method from probably an outside source, it will do the toggling of the canvases for you. This script would need to be placed on something other than the canvases though. Kinda help maybe?