This document is about: FUSION 2
SWITCH TO

Data Streaming

有時需要透過網路發送大量資料,例如在同步玩家構建的地圖時。已連網屬性和遠端程序調用(RPC)(通常不應用於傳輸大型負載)都不適合此任務,而這正是Fusion的資料串流API的用武之地。

NetworkRunnerSendReliableDataToPlayerSendReliableDataToServer方法可用於發送大位元組陣列:

C#

// Large data that needs to be sent
byte[] largeData = new byte [10000];

// Provide 4 numbers as a unique key for the data
var key = ReliableKey.FromInts(42, 0, 0, 0);

// Use in shared mode or as the server/host to send data to players
runner.SendReliableDataToPlayer(playerRef, key, largeData);

// Use as a client to send data to the server/host
runner.SendReliableDataToServer(key, largeData);

在幕後,這個資料將被分割成多個片段,然後串流到伺服器/目標客戶端並重新組裝。

一旦收到完整的資料,叫用INetworkRunnerCallbacks.OnReliableDataReceived回調。提供了一個單獨的回調來追蹤資料傳輸的狀態:

C#

public void OnReliableDataReceived(NetworkRunner runner, PlayerRef player, ReliableKey key, ArraySegment<byte> data) { }

public void OnReliableDataProgress(NetworkRunner runner, PlayerRef player, ReliableKey key, float progress) { }

可以並行串流多組資料,每組資料由一個由16個位元組組成的key來識別(由四個int或兩個ulong建立)。

key還可以用於傳輸中繼資料,例如哪個物件應該負責在接收端處理資料。如果多個類別實作了OnReliableDataReceived回調,並且每個類別只對接收到的資料類型的子集感興趣,則這可能是必要的。

Back to top