Skip to main content
Version: 0.4.1

Goal counter

A goal that counts what hits it, with the same score for everyone. Put it on an object with a solid (not trigger) collider and a TextMeshPro label, then throw something with a Rigidbody and an Object Sync or Pickup into it.

Only the device that simulates a ball (its owner) sees its collisions, so that device reports each goal with a network event to the goal's owner (NetworkEventTarget.Owner). The owner counts it in synced fields, and everyone updates the label in OnDeserialization. Checking Networking.IsOwner(collision.gameObject) makes sure each goal is reported once. Hits slower than minSpeed don't count. See Collisions.

GoalCounter.cs
using StageTime.SDK;
using TMPro;

/// <summary>
/// A goal that counts what hits it, the same for everyone: put it on an object with a solid (not trigger) collider and
/// throw something with a Rigidbody and an Object Sync or Pickup into it. Only the device that simulates the ball (its
/// owner) sees the collision, so that device reports the goal to the goal's owner, who keeps the synced count.
/// Hits slower than <c>minSpeed</c> don't count. Shows <c>OnCollisionEnter</c> / <c>OnCollisionExit</c> with an
/// owner-targeted network event and synced fields.
/// </summary>
public class GoalCounter : StageTimeBehaviour
{
public TMP_Text label;
public float minSpeed = 1f;

[Synced] private int goals;
[Synced, MaxLength(60)] private string last = "";
private int touching; // things touching it that this device simulates

private void Start()
{
Show();
}

private void OnCollisionEnter(UnityEngine.Collision collision)
{
// Report only hits by objects this device simulates, so a goal is counted once however many devices see it.
if (!Networking.IsOwner(collision.gameObject)) return;
touching++;
float speed = collision.relativeVelocity.magnitude;
if (speed >= minSpeed)
SendCustomNetworkEvent(NetworkEventTarget.Owner, nameof(Score), collision.gameObject.name, speed);
Show();
}

private void OnCollisionExit(UnityEngine.Collision collision)
{
if (!Networking.IsOwner(collision.gameObject)) return;
if (touching > 0) touching--;
Show();
}

[NetworkCallable(maxEventsPerSecond: 10)]
public void Score(string what, float speed)
{
if (speed < minSpeed || speed > 100f || what.Length > 30) return; // check values from other devices
StageTimePlayer by = NetworkCalling.CallingPlayer;
goals++;
last = (by != null ? by.displayName : "Someone") + ": " + what + " at " + speed.ToString("0.0") + " m/s";
Show();
}

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

private void Show()
{
if (label == null) return;
string text = "Goals: " + goals + "\nTouching here: " + touching;
if (last != "") text += "\nLast: " + last;
label.text = text;
}
}