https://blog.csdn.net/zhangxiao13627093203/article/details/81026124
1.想要多个客户端操作同一物体,要使该物体从服务器生成,添加NetworkIentity和NetworkTransform制作成预制件并在NetworkManager中注册
2.空物体添加NetworkIdentity,其下SeverOnly勾选意义:作为服务器应用,服务器下激活,在客户端上失活,LocalPlayerAuthority 勾选意义:作为客户端应用
3.非服务器玩家没有权限调用【Commend】方法,但在player 中可以调用,服务器生成的物体同样客户端无法直接用,必须通过服务器调用也就是【Commend】方法
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
public class Player : NetworkBehaviour
{
private Rigidbody rb;
public float MoveSpeed = 8; //水平和垂直的速度
private Camera Camera;
private void Awake()
{
rb = transform.GetComponent<Rigidbody>();
Camera = Camera.main;
}
private void Update()
{
if (!isLocalPlayer) return;
if (Input.GetKeyDown(KeyCode.Space))
{
CmdOpen_door();
}
}
private void FixedUpdate()
{
if (!isLocalPlayer) return; // 如果不是本地角色,就跳过
Vector2 moveDir;
// 获取键盘输入的水平和纵向的值,分别是1和-1,代表两个方向,并传给moveDir这个方向变量
if (Input.GetAxisRaw("Horizontal") == 0 && Input.GetAxisRaw("Vertical") == 0)
{
moveDir.x = 0;
moveDir.y = 0;
}
else
{
moveDir.x = Input.GetAxisRaw("Horizontal");
moveDir.y = Input.GetAxisRaw("Vertical");
Move(moveDir);
}
}
private void LateUpdate()
{
if (!isLocalPlayer) return; // 如果不是本地角色,就跳过
Camera.transform.position = Vector3.Lerp(Camera.transform.position, this.transform.position + new Vector3(0, 2, -5), 5*Time.deltaTime);
}
void Move(Vector2 direction = default(Vector2))
{
if (direction != Vector2.zero) // 如果方向变量不是零向量
{
transform.rotation = Quaternion.LookRotation(new Vector3(direction.x,0, direction.y)); // 调整方向
//transform.forward是一个变量,它是根据当前方向计算出的方向变量
Vector3 movementDir = transform.forward * MoveSpeed * Time.deltaTime; // 当前方向的单位向量 * 速度 * 时间 = 当前方向的偏移量
rb.MovePosition(rb.position + movementDir);
}
}
[Command]
public void CmdOpen_door()
{
if(Door_span.instance!=null)
Door_span.instance.door.transform.Rotate(Vector3.up * 90);
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
/// <summary>
/// 该脚本挂在空物体上 并添加NetworkIdentity 如果勾选SeverOnly 可以用Start 中直接调用
/// 如果没勾选或者勾选LocalPlayerAuthority 想要生成唯一在OnStartServer 中调用
/// 如果没勾选或者勾选LocalPlayerAuthority 想要生成唯一也可将Span_door 方法更改成【Commend】方法,不过不建议,这样会使客户端同样操作但无权限发出警告
/// </summary>
public class Door_span : NetworkBehaviour
{
public static Door_span instance;
[Header("门预制件")]
public GameObject door_prefab;
[HideInInspector]
public GameObject door;
private void Awake()
{
instance = this;
}
private void Start()
{
//Span_door();
}
/// <summary>
/// OnStartServer 只执行一次
/// </summary>
public override void OnStartServer()
{
door = Instantiate(door_prefab, Vector3.zero, Quaternion.identity);//接收
NetworkServer.Spawn(door);
}
//public void Span_door()
//{
// print("进来了");
//door = Instantiate(door_prefab, Vector3.zero, Quaternion.identity);//接收
//NetworkServer.Spawn(door);
//}
}