NetworkObjectProvider
INetworkObjectProvider
當調用Spawned時,在StartGame()
StartArgs
中傳遞的INetworkObjectProvider
處理獲取/建立將附加的遊戲物件。
NetworkObjectProviderDefault
INetworkObjectProvider
的預設實作是NetworkObjectProviderDefault
。如果在啟動運行器時沒有在StartArgs
中指定提供者,運行器將在運行器遊戲物件中搜尋INetworkObjectProvider
元件。如果沒有找到,運行器將自動新增NetworkObjectProviderDefault
。
這個非常基本的實作將通過具現化傳遞的預製件的副本來生成物件,以回應Spawn()
,而不需要任何輪詢。相反,Despawn()
調用是用Destroy()
處理的。
輪詢
建立輪詢物件而不是具現化和銷毀物件的INetworkObjectProvider
的最簡單方法是從NetworkObjectProviderDefalt
衍生並覆寫InstiatePrefab
和DestroyPrefabInstance
:
C#
public class PooledNetworkObjectProvider : NetworkObjectProviderDefault
{
protected override NetworkObject InstantiatePrefab(NetworkRunner runner, NetworkObject prefab)
{
// Get object from pool and return it.
}
protected override void DestroyPrefabInstance(NetworkRunner runner, NetworkPrefabId prefabId, NetworkObject instance)
{
// Return the instance to the pool.
}
}
生成自訂物件
不依賴於重新製作的預製件,而是可以在運行時構建自訂的網路物件。
重要提示: 一旦生成並附加,網路物件就不能新增或刪除網路行為。在生成之前,必須對網路物件上的網路行為進行任何自訂。當然,仍然可以新增及刪除任何非網路元件。
C#
public class BakingObjectProvider : NetworkObjectProviderDefault
{
// For this sample, we are using very high flag values to indicate that we need to do a custom instantiate
// Values lower than this will fall through the default instantiation handling.
public const int CUSTOM_PREFAB_FLAG = 100000;
// The NetworkObjectBaker class can be reused and is Runner independent.
private static NetworkObjectBaker _baker;
private static NetworkObjectBaker Baker => _baker ??= new NetworkObjectBaker();
public override NetworkObjectAcquireResult AcquirePrefabInstance(NetworkRunner runner, in NetworkPrefabAcquireContext context, out NetworkObject result)
{
// Detect if this is a custom spawn by its high prefabID value we are passing.
// The Spawn call will need to pass this value instead of a prefab.
if (context.PrefabId.RawValue == CUSTOM_PREFAB_FLAG)
{
var go = GameObject.CreatePrimitive(PrimitiveType.Cube);
var no = go.AddComponent<NetworkObject>();
go.AddComponent<NetworkTransform>();
go.name = $"Custom Object";
// Baking is required for the NetworkObject to be valid for spawning.
Baker.Bake(go);
// Move the object to the applicable Runner Scene/PhysicsScene/DontDestroyOnLoad
// These implementations exist in the INetworkSceneManager assigned to the runner.
if (context.DontDestroyOnLoad)
{
runner.MakeDontDestroyOnLoad(go);
}
else
{
runner.MoveToRunnerScene(go);
}
// We are finished. Return the NetworkObject and report success.
result = no;
return NetworkObjectAcquireResult.Success;
}
// For all other spawns, use the default spawning.
return base.AcquirePrefabInstance(runner, context, out result);
}
}
Back to top