Advertisement
Munchy2007

Unet5Tut6Pt1HealthAndDamageV1

Feb 28th, 2016
5,884
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.39 KB | None | 0 0
  1. using UnityEngine;
  2. using System.Collections;
  3. using UnityEngine.Networking;
  4.  
  5. public class HealthAndDamage : NetworkBehaviour {
  6.     [SyncVar(hook = "OnHealthChanged")]
  7.     public int health;
  8.     [SyncVar]
  9.     Vector3 respawnPos;
  10.  
  11.     public override void OnStartLocalPlayer ()
  12.     {
  13.         CmdSetHealth(100);
  14.     }
  15.  
  16.     [Command]
  17.     void CmdSetHealth(int newHealth)
  18.     {
  19.         health = newHealth;
  20.     }
  21.  
  22.     [Server]
  23.     public void TakeDamage(GameObject fromPlayer)
  24.     {
  25.         health = Mathf.Max(health - 10, 0);
  26.  
  27.         if(health <= 0)
  28.         {
  29.             DoDeath();
  30.         }
  31.     }
  32.  
  33.     [Server]
  34.     void DoDeath()
  35.     {
  36.         respawnPos = GetRandomSpawnPoint();
  37.         RpcHandlePlayerDeath();
  38.     }
  39.  
  40.     [Server]
  41.     Vector3 GetRandomSpawnPoint()
  42.     {
  43.         var spawnPoints = NetworkManager.singleton.startPositions;
  44.         return spawnPoints[Random.Range(0,spawnPoints.Count)].position;
  45.     }
  46.  
  47.     [ClientRpc]
  48.     void RpcHandlePlayerDeath()
  49.     {
  50.         if(isLocalPlayer)
  51.         {
  52.             transform.position = respawnPos;
  53.             CmdSetHealth(100);
  54.         }
  55.     }
  56.  
  57.  
  58.     void OnHealthChanged(int newHealth)
  59.     {
  60.         health = newHealth;
  61.  
  62.         if(health < 100)
  63.         {
  64.             StartCoroutine(ShowHitEffect());
  65.         }
  66.  
  67.         if(isLocalPlayer)
  68.         {
  69.             HUD.instance.DisplayHealth(health);
  70.         }
  71.     }
  72.  
  73.     IEnumerator ShowHitEffect()
  74.     {
  75.         var material = GetComponent<Renderer>().material;
  76.         Color savedColor = material.color;
  77.         material.color = Color.yellow;
  78.         yield return new WaitForSeconds(0.4f);
  79.         material.color = savedColor;
  80.     }
  81. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement