简体   繁体   中英

Respawn destroyed object in Unity

I have this script where as to when i hit a trigger my enemy spawns at a random time then the enemy destroy itself at a random time. I want to respawn the enemy again so it can do this over and over again. Any Suggestions:

public class SpawnManager : MonoBehaviour {

public GameObject Enemy; // the enemy prefab
public float mytimer; // the time to wait before spawn
public float transport;// the time it has to destroy itself

private GameObject _spawndEnemy; // the enemy that was spawnd

void SpawnEnemy()
{
    var enemySpawnPoint =  GameObject.Find("FFEnemySpawn1").transform;
    _spawndEnemy = Instantiate(
         Enemy, enemySpawnPoint.position, enemySpawnPoint.rotation) as GameObject;
    transport = Random.Range (2,15);
}

void OnTriggerEnter(Collider other)
{
    if (other.gameObject.name == "FFTrigger") {
        mytimer = Random.Range(0,15);
        Invoke("SpawnEnemy", mytimer);
        Debug.Log("Spawn Normal");
    }
}

void Update()
{
    Destroy (_spawndEnemy, transport);
}
}

Hi Ghostdre this question would probably be better answered here Game Dev SO , as for your question I would recommend creating an Enemy class object and data members for the GameObject as well as a time variable which determines how long the Enemy should live before being Destroyed.

eg

public class SpawnManager
{
    public float lifeTime;

    ...

    void Update()
    {
        lifeTime -= Time.deltaTime

        if (lifeTime <= 0)
        {
            Destroy (_spawndEnemy, transport);
            SpawnEnemy()
        }
    }
}

Please note that this is an incomplete example, but it should give you an idea of where to go from here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM