Question by
simplicitydown · Dec 29, 2015 at 03:38 AM ·
2d gamedestroy objectinstantiate-objects
Unable to destroy and instantiate multiple objects in succession?
I am trying to make a object#1 that will destroy itself and have object#2 (a different prefab) instantiate in it's place, and then repeat. Right now my code will destroy the first object and instantiate the second but then will not repeat the sequence- it instantiates the second object and then the same code will not continue the loop of deleting and replacing an object with another object after the first time object#1 gets replaced. Here is the code:
using UnityEngine;
using System.Collections;
public class raisingBlock : MonoBehaviour {
public Transform RaisingBlock;
public GameObject lava1;
public GameObject raisedBlock1;
public GameObject loweredBlock1;
public bool raisingBlockLoop1 = true;
void Start()
{
StartCoroutine("MyEvent");
}
private IEnumerator MyEvent()
{
while(raisingBlockLoop1 == true)
{
yield return new WaitForSeconds(2f);
Destroy(this.gameObject);
Instantiate(lava1,this.transform.position,Quaternion.identity);
yield return new WaitForSeconds(2f);
Destroy(this.gameObject);
Instantiate(raisedBlock1,this.transform.position,Quaternion.identity);
yield return new WaitForSeconds(2f);
Destroy(this.gameObject);
// gameObject.GetComponent<SpriteRenderer>().sprite = Resources.Load<Sprite>("loweredBlock1");
// yield return new WaitForSeconds(4f);
// gameObject.GetComponent<BoxCollider2D>().enabled = true;// wait half a second
// gameObject.GetComponent<SpriteRenderer>().sprite = Resources.Load<Sprite>("lava1");
// yield return new WaitForSeconds(4f);
// gameObject.GetComponent<BoxCollider2D>().enabled = true;// wait half a second
// gameObject.GetComponent<SpriteRenderer>().sprite = Resources.Load<Sprite>("raisedBlock1");
}
}
}
Comment
Answer by simplicitydown · Dec 29, 2015 at 07:38 PM
This works:
private IEnumerator MyEvent()
{
while(raisingBlockLoop1 == true)
{
GameObject Lava = (GameObject)Instantiate(lava1, this.transform.position, Quaternion.identity);
yield return new WaitForSeconds(2f);
Destroy(Lava);
GameObject Raised = (GameObject)Instantiate(raisedBlock1, this.transform.position, Quaternion.identity);
yield return new WaitForSeconds(2f);
Destroy(Raised);
}
}