这阵子学习完SIKI老师的坦克大战,我添加了道具和双人模式后,还想添加一个联机模式。网上找了一下,并没有这个详细教程,所以我把我的开发历程记录下来,希望对道友们有所帮助。
首先说一下要用到的知识点:
1.NetworkManager 组件(基类)和NetworkBehaviour基类
NetworkManager 组件是重要的一个组件(我也不知道要怎么表述,当成网管就好了~)
NetworkBehaviour是我们要做的项目的重要基类,包含了很多API。
这两个基类都继承于我们常用的MonoBehaviour,所以可以放心大胆的把MonoBehaviour改为NetworkBehaviour。
2.我们要牢记,任何需要同步的游戏物体都要添加NetworkIdentity和NetworkTransform组件。
3.Command和ClientRpc。
Command在客户端上被调用,在服务端上执行。
使用方法:[Command] 定义方法名必须以Cmd开头。
ClientRpc在服务端上被调用,在客户端上执行,与Commands相反。
使用方法:[ClientRpc]定义方法名必须以Rpc开头。
4.SyncVar hook
将SyncVar与方法绑定,当SyncVar变化时,绑定的这些方法会在服务端和所有客户端进行同步。我们来看一下官方代码。
using UnityEngine;
using UnityEngine.Networking;
public class Health : NetworkBehaviour
{
public const int m_MaxHealth = 100;
//监听m_CurrentHealth,当他发生变化时会调用OnChangeHealth()方法
[SyncVar(hook = "OnChangeHealth")]
public int m_CurrentHealth = m_MaxHealth;
public RectTransform healthBar;
public void TakeDamage(int amount)
{
if (!isServer)
return;
//Decrease the "health" of the GameObject
m_CurrentHealth -= amount;
//Make sure the health doesn't go below 0
if (m_CurrentHealth <= 0)
{
m_CurrentHealth = 0;
}
}
void Update()
{
//If the space key is pressed, decrease the GameObject's own "health"
if (Input.GetKey(KeyCode.Space))
{
if (isLocalPlayer)
CmdTakeHealth();
}
}
void OnChangeHealth(int health)
{
healthBar.sizeDelta = new Vector2(health, healthBar.sizeDelta.y);
}
//This is a Network command, so the damage is done to the relevant GameObject
[Command]
void CmdTakeHealth()
{
//Apply damage to the GameObject
TakeDamage(2);
}
}
基础的准备工作就这些,详细的知识点我们日后再说。