## 问题
最近跟着一个 MLAPI 教程用 Netcode 做多人联机,到了写玩家移动脚本的时候发现 Client 无法移动位置与转动视角,其它功能都正常。试了试输入都是正常的,最后在 Unity 官网上找到了相应的解释
简单来说就是 NetworkTransform
只允许 Server 向 Client 同步位置,而不允许 Client 自行改变位置,解决办法也很简单,把这个 NetworkTransform
设置为非 ServerAuthoritative
就可以了,以下是示例代码。
解决
using Unity.Netcode.Components;
using UnityEngine;
namespace Unity.Multiplayer.Samples.Utilities.ClientAuthority
{
/// <summary>
/// Used for syncing a transform with client side changes. This includes host. Pure server as owner isn't supported by this. Please use NetworkTransform
/// for transforms that'll always be owned by the server.
/// </summary>
[DisallowMultipleComponent]
public class ClientNetworkTransform : NetworkTransform
{
/// <summary>
/// Used to determine who can write to this transform. Owner client only.
/// This imposes state to the server. This is putting trust on your clients. Make sure no security-sensitive features use this transform.
/// </summary>
protected override bool OnIsServerAuthoritative()
{
return false;
}
}
}
将文件保存为 ClientNetworkTransform.cs
并替换原有 NetworkTransform
即可。
依据官方的说法这样的操作似乎并不是非常安全,但我也就是做个作业,暂时也不用考虑那些问题。
参考
NetworkTransform | Unity Multiplayer Networking (unity3d.com)