'destroy and spawn various objects after certain time
im trying to destroy and respawn them again on old position after a certain time by tag
problems:
- clones not destroyed
- objects dont spawn on the same place as before
- only spawn one after destroy various
[SerializeField]
private GameObject barrel;
private Vector3 position;
private Quaternion rotation;
public int lifetime = 0;
private void Update()
{
var obj = GameObject.Find("barrel");
position = obj.transform.position;
rotation = obj.transform.rotation;
StartCoroutine(Spawn(lifetime));
}
private IEnumerator Spawn(int secs)
{
yield return new WaitForSeconds(secs);
foreach (var b in GameObject.FindGameObjectsWithTag("barrel"))
{
Destroy(b);
Debug.Log("barrel destroyed");
}
Instantiate(barrel, position, rotation);
Debug.Log("barrel spawned");
}
Solution 1:[1]
If you want to destroy and respawn on the same position with a delay, you should use the built in delay on the Destroy function in combination with InvokeRepeating like so, but I would recommend changing the lifetime to something higher than 0:
[SerializeField]
private GameObject barrel;
private Vector3 position;
private Quaternion rotation;
public int lifetime = 1;
private void Start()
{
var obj = GameObject.Find("barrel");
position = obj.transform.position;
rotation = obj.transform.rotation;
//InvokeRepeating(string MethodName, float StartDelay, float RepeatRate)
//This runs the Spawn(); function every 'lifetime' seconds with 0 delay at the start
InvokeRepeating("Spawn", 0, lifetime);
}
private void Update()
{
//No need to run the coroutine every frame
}
private void Spawn()
{
var bar = Instantiate(barrel, position, rotation); //Spawn the barrel but keep a reference to it
Destroy(bar, lifetime); //Destroy the barrel after 'lifetime' seconds
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | A-Fairooz |
