說明:
[Commands]命令是由客戶端(或具有客戶端權限的其他GameObject)發送到服務端,並在服務端運行;
[ClientRpc]命令是由服務端發送到連接到服務端的每一個客戶端並在客戶端運行;
[SyncVar]將服務端的變量同步到客戶端。
1.創建一個Sphere,命名爲Bullet,比例爲(0.2,0.2,0.2),添加NetworkIdentity、NetworkTransform、Rigibody(去掉Use gravity)。拖入Assets,生成預製件Bullet.prefab。刪除場景中的Bullet實體。
2.修改PlayerController.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
//注意繼承至NetworkBehaviour
public class PlayerController : NetworkBehaviour {
//1.新增:子彈prefab
public GameObject bulletPrefab;
//2.新增:子彈初始位置
public Transform bulletSpawn;
void Update()
{
//只操作代表自己的那個Player,如果沒有這個判斷,其他的Player也會跟着動
if (!isLocalPlayer)
return;
var x = Input.GetAxis("Horizontal") * Time.deltaTime * 150.0f;
var z = Input.GetAxis("Vertical") * Time.deltaTime * 3.0f;
transform.Rotate(0, x, 0);
transform.Translate(0, 0, z);
//3.新增:按空格發佈子彈
if (Input.GetKeyDown(KeyCode.Space))
{
CmdFire();
}
}
//
public override void OnStartLocalPlayer()
{
//代表自己的那個Player爲藍色,其他的Player顏色默認
GetComponent<MeshRenderer>().material.color = Color.blue;
}
//4.新增:Command的意思是在服務端執行
[Command]
void CmdFire()
{
GameObject bullet = (GameObject)Instantiate(bulletPrefab, bulletSpawn.position, bulletSpawn.rotation);
bullet.GetComponent<Rigidbody>().velocity = bullet.transform.forward * 6.0f;
//在服務端上生成有速度的子彈
NetworkServer.Spawn(bullet);
//子彈兩秒後銷燬
Destroy(bullet, 2);
}
}
3.將Player.prefab拖入場景,在Player下創建一個Cylinder和一個空物體SpawnPos,Cylinder用戶表示槍管(需要自己調整),SpawnPos用來表示子彈的初始位置,放在槍口。設置PlayerController中的bulletPrefab和bulletSpawn。點擊Inspector上【Apply】按鈕,使預製件的修改生效。刪除場景中的player。
4.將Bullet.prefab拖入NetworkManager的NetworkManager組件【Spawn Info】【Registered Spawnable Prefabs】列表中。
5.發佈測試,客戶端的子彈可以同步了。