Skip to main content

Unity API demo

Exercises transforms, materials, physics, audio, UI and string formatting. See Unity API.

UnityApiDemo.cs
using StageTime.SDK;
using TMPro;
using UnityEngine;

/// <summary>
/// Plain C# and Unity API in a script: arrays, for/while loops, switch, string interpolation, a Light's colour and
/// intensity (synced mode, the clicking player takes ownership) and Rigidbody.AddForce on a ball (a network event, so
/// every client kicks its own copy of the ball the same way).
/// </summary>
public class UnityApiDemo : StageTimeBehaviour
{
public Light demoLight;
public Rigidbody ball;
public TMP_Text label;
public float kickForce = 3f;
public int[] numbers;

[Synced] private int mode;

private int kicks;

private void Start()
{
Apply();
}

public void NextMode()
{
Networking.SetOwner(Networking.LocalPlayer, gameObject);
mode = (mode + 1) % 4;
Apply();
}

public override void OnDeserialization()
{
Apply();
}

public void Kick()
{
SendCustomNetworkEvent(NetworkEventTarget.All, "KickAll");
}

public void KickAll()
{
kicks++;
if (ball != null) ball.AddForce(new Vector3(0.3f, 1f, 0.2f) * kickForce, ForceMode.Impulse);
Apply();
}

private void Apply()
{
string modeName;
Color color;
float intensity;
switch (mode)
{
case 0:
modeName = "warm";
color = new Color(1f, 0.65f, 0.35f);
intensity = 2f;
break;
case 1:
modeName = "cool";
color = new Color(0.35f, 0.6f, 1f);
intensity = 3f;
break;
case 2:
modeName = "green";
color = Color.green;
intensity = 1.5f;
break;
default:
modeName = "off";
color = Color.black;
intensity = 0f;
break;
}
if (demoLight != null)
{
demoLight.color = color;
demoLight.intensity = intensity;
}

int sum = 0;
int max = int.MinValue;
int count = numbers != null ? numbers.Length : 0;
for (int i = 0; i < count; i++)
{
sum += numbers[i];
if (numbers[i] > max) max = numbers[i];
}
int evens = 0;
int k = 0;
while (k < count)
{
if (numbers[k] % 2 == 0) evens++;
k++;
}
float average = count > 0 ? (float)sum / count : 0f;
if (label != null) label.text = $"Mode {mode}: {modeName}\nsum={sum} max={max} evens={evens} avg={Mathf.Round(average * 100f) / 100f}\nkicks={kicks}";
}
}