Skip to content

Communication

Scripts expose public methods. Other scripts call them by holding a reference. There are two cases: engine components and your own script classes.

GameObject.GetComponent<T>() reads a component. Property setters route straight to the native component:

using Kolpa.Engine;
public class Door : MonoBehaviour
{
public override void OnCreate()
{
PhysicsBody body = gameObject.GetComponent<PhysicsBody>();
if (body != null)
{
body.ApplyImpulse(transform.forward * 4f);
}
}
}

GetComponent<T>() only works for types that derive from Component (physics bodies, lights, audio sources, and so on). It returns null when the object has none.

MonoBehaviour has no generic GetComponent<T>() for script classes. To let other code find a script instance, register it in a static table keyed by object id, and look it up when needed. The demo Door does exactly this:

using System.Collections.Generic;
using Kolpa.Engine;
public class Door : MonoBehaviour
{
private static readonly Dictionary<ulong, Door> s_doors = new();
public bool IsLocked { get; private set; }
public static bool TryGet(GameObject go, out Door door)
{
return s_doors.TryGetValue(go.Id, out door!);
}
public override void OnCreate() => s_doors[gameObject.Id] = this;
public override void OnDestroy() => s_doors.Remove(gameObject.Id);
public void SetLocked(bool locked) => IsLocked = locked;
}

Another script resolves it by id:

public class Switch : MonoBehaviour
{
public GameObject DoorObject;
public void Press()
{
if (Door.TryGet(DoorObject, out Door door))
{
door.SetLocked(false);
}
}
}

Register in OnCreate, unregister in OnDestroy. That keeps the table correct across scene loads and hot reload.

GameObject has static lookups:

GameObject doorObject = GameObject.Find("main_door");
GameObject[] enemies = GameObject.FindGameObjectsWithTag("enemy");

Resolve references once in OnCreate and store them in fields. Do not call Find every frame.

For one-to-many notification, use a normal C# event on your own class or a static hub. Unsubscribe in OnDestroy so removed instances stop receiving calls.

public static class GameEvents
{
public static event System.Action<int> ScoreChanged;
public static void RaiseScore(int score) => ScoreChanged?.Invoke(score);
}

Previous: Scene and game state: SceneManager and scene events.

Next: In-game UI: HUD and menus with the UI helpers.