- Home /
Hello everyone A lil stuck in here when I´m trying to spawn an object only ONCE when two objects collide. here´s the code. Thanks in advance.
public GameObject Maze2;
public Transform Spawnpoint;
public void Update()
{
if (GameObject.FindGameObjectWithTag("StarLevel2") == null)
{
Destroy(gameObject, .2f);
Instantiate(Maze2, Spawnpoint.position, Spawnpoint.rotation);
}
}
You instantiate more $$anonymous$$aze2 than one because you're saying spawn $$anonymous$$aze2 as long as StarLevel2 is null. Pretty much it's because it's in Update. I don't really have any good solution but thought I could at least tell you what the problem is. You can Destroy(gameObject); without any delay so that the code won't last long to spawn any more $$anonymous$$aze2 than one. This is all I have ;(
Why don't you use OnTriggerEnter instead? Idk what you're trying to do exactly but I think OnTriggerEnter would work much better for you.
Answer by tocu-adrian · Jul 24, 2020 at 06:44 AM
Hi,
It is not clear why are you using the Update method, if you said that you want to spawn an object when two objects collide, then use OnTriggerEnter or OnCollisionEnter.
But if you want to keep your code, why are you not spawn the object first, and then destroy your gameobject?
And if you want to keep your code like this, i suggest you to use a bool variable. I don't know if this is the most recommended method but i think it works.
public GameObject Maze2;
public Transform Spawnpoint;
private bool _isNull = true;
public void Update()
{
if (GameObject.FindGameObjectWithTag("StarLevel2") == null)
{
Destroy(gameObject, .2f);
if(_isNull)
{
Instantiate(Maze2, Spawnpoint.position, Spawnpoint.rotation);
_isNull = false;
}
}
}
Thanks a lot, it worked like a bliss!! I really apreciate it.