【UNET自学日志】Part10 摧毁玩家

时间:2022-01-14 03:53:46

上一个部分做了玩家的射击造成的伤害,但是玩家生命值为负的时候玩家还在游戏场景上,这个部分我们将要把生命值为0以下的玩家摧毁掉

主要的思路就是当玩家的生命值小于或等于0的时候,将玩家的控制和渲染都设置为不可用即可

将Player_Health脚本做下修改

using UnityEngine;
using System.Collections;
using UnityEngine.Networking;
using UnityEngine.UI;

public class Player_Health : NetworkBehaviour {

    //玩家的生命值,当生命值的数值发生变化时调用OnHealthChanged函数
    [SyncVar(hook="OnHealthChanged")]private int health = 100;

    //右下角显示生命值的Text
    private Text healthText;

    //判断玩家是否死亡的两个bool变量
    private bool shouldDie = false;
    public bool isDead = false;


    public delegate void DieDelegate();
    public event DieDelegate EventDie;

	void Start ()
    {
        healthText = GameObject.Find("Health Text").GetComponent<Text>();
        SetHealthText();
	}
	
	void Update () 
    {
        CheckCondition();
	}

    //检查条件
    void CheckCondition()
    {
        if (health <= 0 && !shouldDie&&!isDead)
        {
            shouldDie = true;
        }

        if (health <= 0 && shouldDie)
        {
            if (EventDie != null)
            {
                EventDie();
            }

            shouldDie = false;
        }
    }

    //设置生命值Text的内容
    void SetHealthText()
    {
        if (isLocalPlayer)
        {
            healthText.text = "Health " + health.ToString();
        }
    }

    //生命值减少
    public void DeductHealth(int dmg)
    {
        health -= dmg;
    }

    //生命值改变
    void OnHealthChanged(int hlth)
    {
        health = hlth;
        SetHealthText();
    }
}


另新建一个脚本Player_Death

using UnityEngine;
using System.Collections;
using UnityEngine.Networking;
using UnityEngine.UI;

public class Player_Death : NetworkBehaviour {

    private Player_Health healthScript;
    //画面中心的小红点
    private Image crossHairImage;


	void Start () 
    {
        crossHairImage = GameObject.Find("crossHairImage").GetComponent<Image>();
        healthScript = GetComponent<Player_Health>();
        healthScript.EventDie += DisablePlayer;
	}

    void OnDisable()
    {
        healthScript.EventDie -= DisablePlayer;
    }
	
    //将Player的相关控制和渲染设置成不可用状态,以代表摧毁Player
    void DisablePlayer()
    {       
        GetComponent<CharacterController>().enabled=false;       
        GetComponent<Player_Shoot>().enabled = false;
        GetComponent<BoxCollider>().enabled = false;

        Renderer[] renderers = GetComponentsInChildren<Renderer>();
        foreach (Renderer ren in renderers)
        {
            ren.enabled = false;
        }

        healthScript.isDead = true;

        if (isLocalPlayer)
        {
            GetComponent<UnityStandardAssets.Characters.FirstPerson.FirstPersonController>().enabled = false;
            crossHairImage.enabled = false;
            //Respawan button 预留重生按钮,下个部分做
        }
    }
}

其中用到了一个委托的方法,因为对委托不是很熟悉,也就不多说些误人子弟的话了。

按着某人的建议写了点注释= =为什么感觉那么鸡肋呢。。。