Hi,
in my c# code i want to destroy an object and instantiate it after some time again.
the problem: the object gets destroyed but not instantiated anymore. can anyone tell me whats wrong with my code?
using UnityEngine;
using System.Collections;
public class InvisiblePlatform : MonoBehaviour {
// Use this for initialization
void Start () {
StartCoroutine(DestroyPlatform());
}
// Update is called once per frame
void Update () {
}
private float platformInvisibleTime = 10f;
IEnumerator DestroyPlatform()
{
GameObject Platform = this.gameObject;
while(true){
Destroy(gameObject);
yield return new WaitForSeconds(platformInvisibleTime);
Instantiate(Platform);
yield return new WaitForSeconds(platformInvisibleTime);
}
}
}
You destroy the game object. So the script on the game object stops running.
You can either move the script onto a controller object and destroy the platform from there. Or if you just want to have the object disappear and reappear change the script to this:
using UnityEngine;
using System.Collections;
public class InvisiblePlatform : MonoBehaviour {
// Use this for initialization
void Start () {
StartCoroutine(DestroyPlatform());
}
// Update is called once per frame
void Update () {
}
private float platformInvisibleTime = 10f;
IEnumerator DestroyPlatform()
{
GameObject Platform = this.gameObject;
while(true){
this.gameObject.renderer.enabled = false; //This hides the mesh
this.gameObject.collider.enabled = false; //This disables the collider so no object can hit it
yield return new WaitForSeconds(platformInvisibleTime);
this.gameObject.renderer.enabled = true; //Shows the mesh again
this.gameObject.collider.enabled = true; //Enables the collider so objects can hit it
yield return new WaitForSeconds(platformInvisibleTime);
}
}
}
Thanks so much, now it works perfectly 