Jason Q
Jason Q

Reputation: 97

Instantiate object at a specific location?

I am just trying to make a square object get destroyed and have a new one instantiated in it's place. What happens now is that the first object is destroyed, and the new one will appear. But it will always appear in the middle of the screen and not in it's parent transform that holds the script. I have tried setting the vectors, using code to set the parent and a few other things but nothing works. Here, and thanks in advance!

public Transform RaisingBlock;
public GameObject lava1;
public GameObject raisedBlock1;
public GameObject loweredBlock1;

void Start()
{
    StartCoroutine("MyEvent");
}

private IEnumerator MyEvent()
{
    while(true)
    {
        yield return new WaitForSeconds(2f);
        Destroy(this.gameObject); 
        Instantiate(lava1);
    }
}

Upvotes: 1

Views: 1591

Answers (1)

mahdi mahzouni
mahdi mahzouni

Reputation: 474

When you destroy the gameObject, it gets deleted from the active screen. So its location will be lost as well. But the problem here is that you should state the location when you instantiate the lava1 object. Consider using one of the overloads of Instantiate to accomplish this:

Instantiate(lava1, this.gameObject.transform.position, 
            this.gameObject.transform.rotation);

Also, your coroutine stops because your script gets destroyed along with the gameObject.

Upvotes: 2

Related Questions