Home > Software design >  Having trouble deleting a prefab after instantiating inside a coroutine
Having trouble deleting a prefab after instantiating inside a coroutine

Time:07-27

I'm initiating prefab inside a coroutine and deleting it after one second like this:

Vector2 spawnPos = Camera.main.ViewportToWorldPoint(new Vector3(0.5f, 0.5f,5.0f));
Instantiate(_Confirm, spawnPos, Quaternion.identity);
yield return new WaitForSeconds(1);
Destroy(_Confirm);

But the only problem is the object won't get deleted. I even tried SetActive(false), but that didn't work either.

What am I doing wrong?

EDIT: Full Code:

_tick.SetActive(true);
        //yield return new WaitForSeconds(1);
        _soilPatch=GameObject.FindGameObjectWithTag("Selected");
        Instantiate(_flower,new Vector3(_soilPatch.transform.position.x,_soilPatch.transform.position.y 1.3f,_soilPatch.transform.position.z),Quaternion.identity);
        _soilPatch.tag="Untagged";
        _soilPatch.SetActive(false);
        _uI.SetActive(false);
        _tick.SetActive(false);
        Vector2 spawnPos = Camera.main.ViewportToWorldPoint(new Vector3(0.5f, 0.5f,5.0f));
        GameObject g = Instantiate(_Confirm, spawnPos, Quaternion.identity);
        yield return new WaitForSeconds(1);
        Destroy(g)

CodePudding user response:

You need to assign a reference to the object you're instantiating:

Vector2 spawnPos = Camera.main.ViewportToWorldPoint(new Vector3(0.5f, 0.5f,5.0f));
GameObject g = Instantiate(_Confirm, spawnPos, Quaternion.identity);
yield return new WaitForSeconds(1);
Destroy(g);
  • Related