Dice roller
A die that anyone can roll. The roller's device picks the number and a colour and sends both to everyone with
SendCustomNetworkEvent. ShowRoll is a [NetworkCallable] event:
it checks the number, shows who rolled it with NetworkCalling.CallingPlayer, tints the die and keeps the last five
rolls. Each player can roll at most twice a second.
Put it on an interactable object, set Label to a TextMeshPro label and Dice to the die's renderer.
DiceRoller.cs
using StageTime.SDK;
using TMPro;
using UnityEngine;
/// <summary>
/// Dice roller (network events with arguments): Roll picks a number and a colour on the roller's device and sends them
/// to everyone with SendCustomNetworkEvent(All, nameof(ShowRoll), value, tint). ShowRoll is [NetworkCallable]: it
/// checks the number (it comes from another player's device), shows who rolled it with NetworkCalling.CallingPlayer and
/// keeps the last five rolls. Each player can roll at most twice a second.
/// </summary>
public class DiceRoller : StageTimeBehaviour
{
public TMP_Text label;
public Renderer dice;
private readonly string[] lines = new string[5];
private int rolls;
private void Start()
{
Show();
}
public override void Interact()
{
Roll();
}
public void Roll()
{
int value = Random.Range(1, 7);
Color tint = Color.HSVToRGB(Random.value, 0.6f, 1f);
SendCustomNetworkEvent(NetworkEventTarget.All, nameof(ShowRoll), value, tint);
}
[NetworkCallable(maxEventsPerSecond: 2)]
public void ShowRoll(int value, Color tint)
{
if (value < 1 || value > 6) return; // arguments come from another player's device: check them
StageTimePlayer roller = NetworkCalling.CallingPlayer;
string name = roller != null ? roller.displayName : "Someone";
for (int i = lines.Length - 1; i > 0; i--) lines[i] = lines[i - 1];
lines[0] = name + " rolled " + value;
rolls++;
if (dice != null) dice.material.color = tint;
Show();
}
private void Show()
{
if (label == null) return;
string text = "Rolls: " + rolls;
foreach (string line in lines)
if (line != null) text += "\n" + line;
label.text = text;
}
}