简体   繁体   中英

Problem with unity c# - Object.Destroy not working

So I am creating many objects in coroutine and of course I want to delete them, but Object.Destroy doesnt work. Any ideas?

`public class Spawner : MonoBehaviour
{
    [SerializeField] Obstacle obstaclePrefab;
    private void Start()
    {
        StartCoroutine(SpawnNewObstacle());
    }
    IEnumerator SpawnNewObstacle()
    {
        do
        {
            float range = Random.Range(-2.55f, 3.35f);
            Vector3 position = new Vector3(12.5f, range, -1);
            var obstacle = Instantiate(obstaclePrefab, position, Quaternion.identity);
            yield return new WaitForSeconds(2f);
            DestroyImmediate(obstacle);
        }
        while (true);
    }
}`

I guess, instead of DestroyImmediate you are using Object.Destroy , which is a recommended practice.

Eventually the objects gets destroyed, the destruction is delayed till the objects do not have any refernces.

Especially when you are using coroutines, the execution is paused and the control is returned to the calling code and your objects may be still in use. In that case, the delay in destruction is more visible.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM