I want to spawn a GameObject in Unity when the Scene has been active for 9 secconds. I used Time.timeSinceStartup but it starts to count secconds since i start the whole game. Does anybody know which is the script to start counting the time from the start of a scene?
CodePudding user response:
There are about 100 ways to achieve what you want to do (mainly coroutines) however I am assuming you are just getting started therefore in my opinion the easiest way to do it is this.
Attach this script to an empty gameobject in the scene. (Note: this script destroys itself but not the gameobject. If you want to destroy gameobject, instead of "this" write "gameobejct".)
using UnityEngine;
public class SpawnDelay : MonoBehaviour
{
[SerializeField] GameObject Prefab;
[SerializeField] float DelayInSeconds;
float timer;
void Update()
{
timer = Time.deltaTime;
if(timer >= DelayInSeconds)
{
Instantiate(Prefab);
Destroy(this); //Destroys itself to save memory
}
}
}