Unity Multiplayer MLAPI 无法获取 NetworkBehaviour 的 NetworkObject

Unity Multiplayer MLAPI Could not get NetworkObject for the NetworkBehaviour

对于我的 PlayerController 脚本,我将继承从 MonoBehaviour 更改为 NetworkBehaviour

public class PlayerController : MonoBehaviour
{

从这里,到这里:

public class PlayerController : NetworkBehaviour
{

尽管我的播放器控制器对象确实有一个 NetworkObject 组件。

它抛出一个错误,说它没有。

NullReferenceException: Could not get NetworkObject for the NetworkBehaviour. Are you missing a NetworkObject component?
MLAPI.NetworkBehaviour.get_NetworkObject () (at Library/PackageCache/com.unity.multiplayer.mlapi@3e3aef6aa0/Runtime/Core/NetworkBehaviour.cs:282)
MLAPI.NetworkObject.get_ChildNetworkBehaviours () (at Library/PackageCache/com.unity.multiplayer.mlapi@3e3aef6aa0/Runtime/Core/NetworkObject.cs:515)
MLAPI.NetworkObject.ResetNetworkStartInvoked () (at Library/PackageCache/com.unity.multiplayer.mlapi@3e3aef6aa0/Runtime/Core/NetworkObject.cs:472)
MLAPI.Spawning.NetworkSpawnManager.SpawnNetworkObjectLocally (MLAPI.NetworkObject networkObject, System.UInt64 networkId, System.Boolean sceneObject, System.Boolean playerObject, System.Nullable`1[T] ownerClientId, System.IO.Stream dataStream, System.Boolean readPayload, System.Int32 payloadLength, System.Boolean readNetworkVariable, System.Boolean destroyWithScene) (at Library/PackageCache/com.unity.multiplayer.mlapi@3e3aef6aa0/Runtime/Spawning/NetworkSpawnManager.cs:395)
MLAPI.NetworkManager.StartHost (System.Nullable`1[T] position, System.Nullable`1[T] rotation, System.Nullable`1[T] createPlayerObject, System.Nullable`1[T] prefabHash, System.IO.Stream payloadStream) (at Library/PackageCache/com.unity.multiplayer.mlapi@3e3aef6aa0/Runtime/Core/NetworkManager.cs:556)
NetworkManagerEditor.OnInspectorGUI () (at Library/PackageCache/com.unity.multiplayer.mlapi@3e3aef6aa0/Editor/NetworkManagerEditor.cs:371)
UnityEditor.UIElements.InspectorElement+<>c__DisplayClass59_0.<CreateIMGUIInspectorFromEditor>b__0 () (at <31768fe99cfe4466aa4a401169fb2ce5>:0)
UnityEngine.GUIUtility:ProcessEvent(Int32, IntPtr, Boolean&)

我在网络管理器上单击“启动主机”后立即抛出此错误 script/object。

我该如何解决这个问题?

出于某种原因。存在使 GetComponentInParent return 为空的竞争条件。所以我编辑 NetworkBehaviour.cs 改为使用 GetComponent

    /// <summary>
    /// Gets the NetworkObject that owns this NetworkBehaviour instance
    /// </summary>
    public NetworkObject NetworkObject
    {
        get
        {
            if (m_NetworkObject == null)
            {
                //m_NetworkObject = GetComponentInParent<NetworkObject>();

                m_NetworkObject = GetComponent<NetworkObject>();
            }

            if (m_NetworkObject == null)
            {
                throw new NullReferenceException($"Could not get {nameof(NetworkObject)} for the {nameof(NetworkBehaviour)}. Are you missing a {nameof(NetworkObject)} component?");
            }

            return m_NetworkObject;
        }
    }