脚本示例

知识问答

从网络上的 JSON 文件加载问题,并同步当前问题,让所有人玩同一轮。

问题文件

通过 https 托管一个 JSON 文件:

{ "questions": [
  { "q": "What does BEE stand for?", "a": ["Basis Encrypted Experience", "Big Event Engine"], "correct": 0 }
] }

脚本

TriviaQuiz.cs (Cilbox)
using Basis;
using Basis.Network.Core;
using Basis.Scripts.Networking.NetworkedAvatar;
using Basis.Shims;
using Cilbox;
using TMPro;
using UnityEngine;

[Cilboxable]
public class TriviaQuiz : MonoBehaviour
{
    public string url = "https://example.github.io/questions.json";
    public TextMeshPro questionLabel;
    public TextMeshPro[] answerLabels;

    BasisNetworkShim net;
    BasisJsonNode questions;
    int index;

    void Start()
    {
        net = GetComponent<BasisNetworkShim>();
        net.NetworkMessageReceived += OnMessage;
        net.PlayerJoined += OnPlayerJoined;
        questionLabel.text = "Loading...";
        new BasisStringDownloader().DownloadString(url, result =>
        {
            if (!result.Success) { questionLabel.text = "Could not load questions"; return; }
            BasisJsonNode root = BasisJson.Parse(result.Result);
            questions = root != null ? root.Get("questions") : null;
            Show();
        });
    }

    public void NextQuestion()
    {
        if (questions == null || questions.Count == 0) return;
        net.TakeOwnership();
        index = (index + 1) % questions.Count;
        Show();
        if (net.HasNetworkID) net.SendCustomNetworkEvent(new[] { (byte)index }, DeliveryMethod.ReliableOrdered);
    }

    void OnMessage(ushort sender, byte[] data, DeliveryMethod method)
    {
        if (data == null || data.Length < 1) return;
        index = data[0];
        Show();
    }

    void OnPlayerJoined(BasisNetworkPlayer player)
    {
        if (net.HasNetworkID && net.IsOwnedLocallyOnServer) net.SendCustomNetworkEvent(new[] { (byte)index }, DeliveryMethod.ReliableOrdered, new[] { player.playerId });
    }

    void Show()
    {
        if (questions == null || index >= questions.Count) return;
        BasisJsonNode q = questions.Get(index);
        questionLabel.text = q.GetString("q", "");
        string[] answers = q.GetStringArray("a");
        for (int i = 0; i < answerLabels.Length; i++) answerLabels[i].text = i < answers.Length ? answers[i] : "";
    }
}
  • 只同步问题索引;每个客户端都下载同一个文件。
  • 玩家首次需要批准该主机。在此之前,标牌会显示正在加载。
Edit on GitHub

Last updated on

On this page