Unity多人遊戲簡單實例(一)同步變量

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

public class Health : NetworkBehaviour
{
	public const int maxHealth = 100;

	//需要同步的變化
	[SyncVar(hook ="OnChangeHealth")]
	public int currentHealth = maxHealth;

	//血條
	public RectTransform healthbar;

	public void TakeDamage(int amount)
	{
		//爲了保持變量一致,作爲服務端時才處理
		if (!isServer)
			return;

		currentHealth -= amount;
		if(currentHealth <=0)
		{
			currentHealth = 0;
			Debug.Log("Dead");
		}		
	}

	//變量改變是客戶端處理
	void OnChangeHealth(int health)
	{
		//修改血條
		healthbar.sizeDelta = new Vector2(health * 2, healthbar.sizeDelta.y);
	}
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章