This document is about: FUSION 2
SWITCH TO

Simulation Behaviour

概述

SimulationBehaviourNetworkBehaviour的基礎類別,可用於安全造訪Fusion的更新方法
諸如FixedUpdateNetworkRender等方法,而不需要NetworkObject

SimulationBehaviour不能具有任何已連網屬性,也不能與NetworkObject一起使用。
它們需要使用NetworkRunner.AddGlobal()NetworkRunner上手動登錄。與NetworkRunner.位於同一GameObject上的SimulationBehaviours不需要登錄

登錄/取消登錄SimulationBehaviours

必須手動登錄與NetworkRunner不連接到同一GameObjectSimulationBehavior
一種安全的方法是使用NetworkRunner.GetRunnerForGameObject()方法來查找正確的運行器參照,如下所示。

C#

public void RegisterOnRunner() {
      // Find the network runner for this gameobject scene. This is useful on a scene object.
      var runner = NetworkRunner.GetRunnerForGameObject(gameObject);

      // Make sure the network runner is started and running.
      if (runner.IsRunning) {
        runner.AddGlobal(this);
      }
    }

    public void RemoveFromRunner() {
      // The same process can be done to remove the SimulationBehaviour.
      var runner = NetworkRunner.GetRunnerForGameObject(gameObject);
      if (runner.IsRunning) {
        runner.RemoveGlobal(this);
      }
    }

使用示例

SimulationBehavior可用於存取Fusion的內部邏輯,但它們不能具有已連網屬性,也不能與其他同儕節點同步。
它非常適合像權威伺服器遊戲上的物品或強化物生成器這樣的場景,
在這種場景中,客戶端不應該知道生成邏輯,而只需要複製生成的強化物或物品本身。

以下是一個使用SimulationBehaviour的強化物生成器的示例:

C#

public class BasicPowerUpSpawner : SimulationBehaviour {

    // Local list of prefabs for the available power ups to be spawned.
    [SerializeField] private List<NetworkPrefabRef> _availablePowerUps = new List<NetworkPrefabRef>();

    private float _spawnDelay = 3f;

    public void RegisterOnRunner() {
      // Find the network runner for this gameobject scene. This is useful on a scene object.
      var runner = NetworkRunner.GetRunnerForGameObject(gameObject);

      // Make sure the network runner is started and running.
      if (runner.IsRunning) {
        runner.AddGlobal(this);
      }
    }

    public void RemoveFromRunner() {
      // The same process can be done to remove the SimulationBehaviour.
      var runner = NetworkRunner.GetRunnerForGameObject(gameObject);
      if (runner.IsRunning) {
        runner.RemoveGlobal(this);
      }
    }

    public override void FixedUpdateNetwork() {
      if (Runner.Tick % Mathf.RoundToInt(Runner.TickRate * _spawnDelay) == 0) {
        // Generate a random index to select a power up from the list.
        int randomIndex = Random.Range(0, _availablePowerUps.Count);
        // Spawn the selected power up.
        Runner.Spawn(_availablePowerUps[randomIndex]);
      }
    }
  }

請注意,此指令碼不會在NetworkRunner上登錄自己,但它確實有需要按需調用的登錄方法。可用強化物清單是僅對主機端/伺服器執行個體重要的本機清單,
但是,生成的強化物NetworkObjects將被正確複製到所有客戶端,而無需了解生成邏輯。

Back to top