unity3D使用协程控制怪物的死亡04
使激活状态的怪变为未激活状态
private void DeActiveMonster()
{
if (activeMonster != null)
{
activeMonster.GetComponent<BoxCollider>().enabled = false;
activeMonster.SetActive(false);
activeMonster = null;
}
}
不同时间调用方法:迭代器(死亡计时器)
先生成怪物,再让怪物死亡
消失要在出现之后
start方法中,函数只执行一次
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TargetManager : MonoBehaviour
{
//1.获取我们设置的四种怪物:控制怪物的生成或销毁(显示或隐藏) 最开始是都不显示
//2.建立数组
public GameObject[] monsters;
//6.获得激活状态的怪物
public GameObject activeMonster = null;
//9.调用测试
private void Start()
{
//10.遍历初始化目标怪的状态以及boxcollider状态
foreach (GameObject monster in monsters)
{
monster.GetComponent<BoxCollider>().enabled = false;
monster.SetActive(false);
}
//ActiveMonster();
//12.调用迭代器方法:先注释上一句的直接调用
StartCoroutine("AliveTimer");
//14.调用
StartCoroutine("DeathTimer");
}
//3.是否激活各种状态函数
private void ActiveMonster()
{
//4.随机激活:得到index
int index = Random.Range(0, monsters.Length);
//5.激活怪物:需要先获得激活状态的怪物
//赋值
activeMonster = monsters[index];
//7.激活
activeMonster.SetActive(true);
//8.激活box collider
activeMonster.GetComponent<BoxCollider>().enabled = true;
}
//11.协程控制迭代器 设置怪物生成的等待时间
IEnumerator AliveTimer()
{
yield return new WaitForSeconds(Random.Range(1, 5));
ActiveMonster();
}
//14.控制死亡迭代器 使激活状态的怪变为未激活状态
private void DeActiveMonster()
{
if (activeMonster != null)
{
activeMonster.GetComponent<BoxCollider>().enabled = false;
activeMonster.SetActive(false);
activeMonster = null;
}
}
//设置死亡时间
IEnumerator DeathTimer()
{
yield return new WaitForSeconds(Random.Range(5,10));
DeActiveMonster();
}
}
不断生成怪物
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TargetManager : MonoBehaviour
{
//1.获取我们设置的四种怪物:控制怪物的生成或销毁(显示或隐藏) 最开始是都不显示
//2.建立数组
public GameObject[] monsters;
//6.获得激活状态的怪物
public GameObject activeMonster = null;
//9.调用测试
private void Start()
{
//10.遍历初始化目标怪的状态以及boxcollider状态
foreach (GameObject monster in monsters)
{
monster.GetComponent<BoxCollider>().enabled = false;
monster.SetActive(false);
}
//ActiveMonster();
//12.调用迭代器方法:先注释上一句的直接调用
StartCoroutine("AliveTimer");
}
//3.是否激活各种状态函数
private void ActiveMonster()
{
//4.随机激活:得到index
int index = Random.Range(0, monsters.Length);
//5.激活怪物:需要先获得激活状态的怪物
//赋值
activeMonster = monsters[index];
//7.激活
activeMonster.SetActive(true);
//8.激活box collider
activeMonster.GetComponent<BoxCollider>().enabled = true;
//14.调用
StartCoroutine("DeathTimer");
}
//11.协程控制迭代器 设置怪物生成的等待时间
IEnumerator AliveTimer()
{
yield return new WaitForSeconds(Random.Range(1, 5));
ActiveMonster();
}
//14.控制死亡迭代器 使激活状态的怪变为未激活状态
private void DeActiveMonster()
{
if (activeMonster != null)
{
activeMonster.GetComponent<BoxCollider>().enabled = false;
activeMonster.SetActive(false);
activeMonster = null;
}
//14.再次激活
StartCoroutine("AliveTimer");
}
//设置死亡时间
IEnumerator DeathTimer()
{
yield return new WaitForSeconds(Random.Range(3,8));
DeActiveMonster();
}
}