This document is about: FUSION 2
SWITCH TO

Networking Fusion Object Types

概述

NetworkObjectNetworkBehaviour參照可以是NetworkBehaviour的已連網屬性。(注意: 這些在INetworkStruct中無效)。

在內部,這些已連網的NetworkObjectNetworkBehaviour參照被轉換為NetworkIdNetworkBehaviourId值。

ILWeaver生成的Set方法將參照轉換(包裝)為其ID,而該ID就是已連網ID。

ILWeaver生成的Get方法使用Runner.TryGetObject()Runner.TryGetBehaviour()方法將ID轉換(解包)為參照。

C#

[Networked] public NetworkObject MyNetworkObject { get; set; }
[Networked] public CustomNetworkBehaviour MyNetworkBehaviour { get; set; }

雖然方便,但這種自動化確實意味著:

  • 顯式空值,及;
  • 未能解包

兩者都將為Get返回空值,兩者之間沒有區別。

對屬性使用NetworkObjectNetworkBehaviour的另一種方法是使用NetworkIdNetworkBehaviourId值。

透過ID顯式同步這些參照,您可以檢測空值是否:

  • 表示顯式空值(0),或;
  • 表示一個物件(值>0),但該物件當前在本機不存在(無法解包)。

NetworkId用途示例

C#

using Fusion;

public class SyncNetworkObjectExample : NetworkBehaviour
{
  // NetworkId is backed by one int value.
  // A zero value (default) represents null.
  [Networked] public NetworkId SyncedNetworkObjectId { get; set; }

  private void SetObject(NetworkObject netObj)
  {
    SyncedNetworkObjectId = netObj != null ? netObj.Id : default;
  }

  bool TryResolve(out NetworkObject no)
  {
    // A default (0) value indicates an explicit null value.
    // Return true to represent successfully resolving this to null.
    if (SyncedNetworkObjectId == default)
    {
      no = null;
      return true;
    }

    // Find the object using the non-null id value.
    // Return true if the lookup was successful.
    // Return false and null if the NetworkObject could not be found on the local Runner.
    bool found = Runner.TryFindObject(SyncedNetworkObjectId, out var obj);
    no = obj;
    return found;
  }
}

NetworkBehaviourId用途示例

C#

using Fusion;

public class SyncNetworkBehaviourExample : NetworkBehaviour
{
  // NetworkId is backed by two int values.
  // Object = NetworkObject.Id (value of 0 represents null/Invalid).
  // Behaviour = NetworkBehaviour index in GameObject hierarchy.
  [Networked] public NetworkBehaviourId SyncedNetworkBehaviourId { get; set; }

  private void SetBehaviour(NetworkBehaviour nb)
  {
    SyncedNetworkBehaviourId = nb != null ? nb.Id : default;
  }

  bool TryResolve(out NetworkBehaviour no)
  {
    // A default (0) value indicates an explicit null value.
    // Return true to represent successfully resolving this to null.
    if (SyncedNetworkBehaviourId == default)
    {
      no = null;
      return true;
    }

    // Find the NetworkBehaviour using the non-default id value.
    // Return true if the lookup was successful.
    // Return false and null if the NetworkObject could not be found on the local Runner.
    bool found = Runner.TryFindBehaviour(SyncedNetworkBehaviourId, out var obj);
    no = obj;
    return found;
  }
}
Back to top