射击类项目(数据的持久化保存)整理四

1.TargetManager.cs 目标位置管理器
一个位置写可以有多种不同的怪物类型,随机出现。从下图可以看出一共有9个位置,每个位置有4种怪物类型。
在这里插入图片描述

记录变量

	//保存所有该目标下的怪物
    public GameObject[] monsters;
	//保存目前处于激活状态的怪物
    public GameObject activeMonster = null;
	//表示目标所在的位置(0-8)
	public int targetPosition;

由于有9个位置,都要调用,所以此处不能再用单例模式

	//public static TargetManager _intance;
	
    private void Awake()
    {
		//由于有9个位置,都要调用,所以此处不能再用单例模式
        //_intance = this;
    }

在程序的一开始先关闭所有的碰撞、隐藏所有怪物(避免上一次操作没有关闭、隐藏)

    private void Start()
    {
        foreach(GameObject monster in monsters)
        {
            monster.GetComponent<BoxCollider>().enabled = false;
            monster.SetActive(false);
        }
        //调用协程
        StartCoroutine("AliveTimer");
    }

协程随机等待1-4秒,再激活怪物出现

 //迭代器方法(协程),设置生成的等待时间
    IEnumerator AliveTimer()
    {
        //等待1-4秒后执行ActivateMonster方法
        yield return new WaitForSeconds(Random.Range(1, 5));
        ActivateMonster();
    }

激活怪物出现

//随机激活怪物
    private void ActivateMonster()
    {
        int index = Random.Range(0, monsters.Length);
        activeMonster = monsters[index];
        activeMonster.SetActive(true);
        activeMonster.GetComponent<BoxCollider>().enabled = true;
        //调用死亡时间的协程
        StartCoroutine("DeathTimer");
    }

怪物出现一定时间后,自己销毁

//迭代器(协程),设置死亡的等待时间
    IEnumerator DeathTimer()
    {
        yield return new WaitForSeconds(Random.Range(3, 8));
        DeActivateMonster();
    }

怪物自己销毁(隐藏)

//使激活状态的怪物变为未激活状态
    private void DeActivateMonster()
    {
        if (activeMonster != null)
        {
            activeMonster.GetComponent<BoxCollider>().enabled = false;
            activeMonster.SetActive(false);
            activeMonster = null;
        }
        //调用激活时间的协程,达到一个反复激活和死亡的循环
        StartCoroutine("AliveTimer");
    }

更新生命周期。当子弹击中怪物时,或者重新开始游戏时
停止所有的协程
将当前处于激活状态的怪物变为未激活状态,清空activeMonster
重新开始AliveTimer的协程(随机激活怪物)

    public void UpdateMonsters()
    {
        StopAllCoroutines();
        if (activeMonster != null)
        {
			activeMonster.GetComponent<BoxCollider>().enabled = false;
			activeMonster.SetActive(false); 
            activeMonster = null;         
        }
        StartCoroutine("AliveTimer");
    }

按照指定的类型激活怪物
停止所有协程
将当前激活状态的怪物(如果有的话),转变为未激活状态
激活给定类型的怪物
调用死亡时间的协程
用于加载游戏,先隐藏当前所有出现的怪物,再按照之前存储的怪物类型,显示指定的怪物

	public void ActiveMonsterByType(int type)
	{
		StopAllCoroutines();
		if (activeMonster != null)
		{
			activeMonster.GetComponent<BoxCollider>().enabled = false;
			activeMonster.SetActive(false);
			activeMonster = null;
		}
		activeMonster = monsters[type];
		activeMonster.SetActive(true);
		activeMonster.GetComponent<BoxCollider>().enabled = true;
		StartCoroutine("DeathTimer");
	}  
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值