上一部分我们做的是射击的部分,说到射击,肯定和伤害有关,当Player1击中Player2的时候,将会造成Player2生命值的减少
本部分也较为容易,我们需要一个新的脚本Player_Health,另外,我们需要对上一次做的Player_Shoot脚本留下的东西做完
using UnityEngine;
using System.Collections;
using UnityEngine.Networking;
using UnityEngine.UI;
public class Player_Health : NetworkBehaviour {
[SyncVar(hook="OnHealthChanged")]private int health = 100;
private Text healthText;
void Start ()
{
healthText = GameObject.Find("Health Text").GetComponent<Text>();
SetHealthText();
}
void SetHealthText()
{
if (isLocalPlayer)
{
healthText.text = "Health " + health.ToString();
}
}
public void DeductHealth(int dmg)
{
health -= dmg;
}
void OnHealthChanged(int hlth)
{
health = hlth;
SetHealthText();
}
}
using UnityEngine;
using System.Collections;
using UnityEngine.Networking;
public class Player_Shoot : NetworkBehaviour {
private int damage = 25;
private float range = 200;
[SerializeField]private Transform camTransform;
private RaycastHit hit;
void Update ()
{
CheckIfShooting();
}
void CheckIfShooting()
{
if (!isLocalPlayer)
{
return;
}
if (Input.GetKeyDown(KeyCode.Mouse0))
{
Shoot();
}
}
void Shoot()
{
if (Physics.Raycast(camTransform.TransformPoint(0, 0, 0.5f), camTransform.forward, out hit, range))
{
//Debug.Log(hit.transform.tag);
if (hit.transform.tag == "Player")
{
string uIdentity = hit.transform.name;
CmdTellServerWhoWasShot(uIdentity, damage);
}
}
}
[Command]
void CmdTellServerWhoWasShot(string uniqueID, int dmg)
{
GameObject go = GameObject.Find(uniqueID);
go.GetComponent<Player_Health>().DeductHealth(dmg);
}
}
当Player1击中Player2的时候,告诉服务器它击中的是哪一个Player,然后调用Player_Health脚本中的DeductHealth函数,Player2的生命值减少