This document is about: FUSION 2
SWITCH TO

Simulation Behaviour

概要

SimulationBehaviourNetworkBehaviourの基底クラスで、NetworkObjectを使わずにFusionの更新メソッド(FixedUpdateNetworkRenderなど)へ安全にアクセスするために使用できます。

SimulationBehaviourはネットワークプロパティを持つことはできず、ネットワークオブジェクトでの使用は想定されていません。 SimulationBehaviourは、NetworkRunner.AddGlobal()を使用してNetworkRunnerに手動で登録する必要がありますが、NetworkRunnerと同じゲームオブジェクトにある場合は登録は不要です。

SimulationBehaviour の登録/登録解除

NetworkRunnerと同じゲームオブジェクトに追加されていないSimulationBehaviourは、手動で登録が必要です。 これを安全に実行する方法は、NetworkRunner.GetRunnerForGameObject()メソッドを使用して、正しいNetworkRunnerの参照を検索することです。

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);
      }
    }

使用例

SimulationBehaviourは、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に登録するメソッドを呼び出す必要があります。パワーアップアイテムのリストは、サーバーにのみ重要な情報になるため、ローカルのリストになっていますが、出現したパワーアップアイテムのNetworkObjectはすべてのクライアントに正しく複製されるため、クライアントがその出現ロジックを知る必要はありません。

Back to top