雖然敵人物件可以被子彈攻擊並且造成傷害,但是當敵人的血量歸零時,該物件應該要被銷毀。
要做到這件事,我們需要調整Health腳本,最簡單的方法是使用一個布林變數DestroyOnDeath,來調整該物件是否在死亡時銷毀。
開啟Health腳本,修改以下內容,新增布林變數DestroyOnDeath,接著用if (destroyOnDeath)判斷是否要銷毀該物件:
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Networking;
using System.Collections;
public class Health : NetworkBehaviour {
public const int maxHealth = 100;
public bool destroyOnDeath;
[SyncVar(hook = "OnChangeHealth")]
public int currentHealth = maxHealth;
public RectTransform healthBar;
public void TakeDamage(int amount)
{
if (!isServer)
return;
currentHealth -= amount;
if (currentHealth <= 0)
{
if (destroyOnDeath)
{
Destroy(gameObject);
}
else
{
currentHealth = maxHealth;
// called on the Server, will be invoked on the Clients
RpcRespawn();
}
}
}
void OnChangeHealth (int currentHealth)
{
healthBar.sizeDelta = new Vector2(currentHealth, healthBar.sizeDelta.y);
}
[ClientRpc]
void RpcRespawn()
{ if (isLocalPlayer)
{
// Set the player’s position to origin
transform.position = Vector3.zero;
}
}
}
編譯後將Enemy prefab的Health腳本下的DestroyOnDeath的變數改為true。
現在我們編譯後可以進行測試,測試連線時結果的方法點我。
現在射擊敵人時會使它們的血量下降,當血量降至零,敵人物件會被銷毀,而玩家物件因為沒有做DestroyOnDeath的更動,所以和之前一樣,死亡時會恢復血量並回到原點。
上一篇:處理非玩家角色物件
下一篇:生成和重生
建立一個簡單的多人連線範例

沒有留言:
張貼留言