Skip to content

Gameplay scripts

A gameplay script drives one GameObject: a door, a pickup, the player, a moving platform, and so on. Every placed copy of that prefab runs its own instance of the script class.

  1. Select the GameObject in the Scene Hierarchy.
  2. In the inspector, Add Component -> Script.
  3. In the Behaviour field, type the type name, for example Kolpa.Demo.Door, Kolpa.Demo.

To place a script on many objects, add the same type to each. Each GameObject gets its own instance with its own field values.

Derive from MonoBehaviour. The gameObject and transform properties point at the object the script is attached to.

using System;
using Kolpa.Engine;
public class Door : MonoBehaviour
{
public float OpenAngle = 100f;
public float OpenSpeed = 180f;
private bool _open;
private float _angle;
public override void OnCreate()
{
Log($"Door on '{gameObject.name}'");
}
public override void OnUpdate(float deltaTime)
{
float target = _open ? OpenAngle : 0f;
float step = OpenSpeed * deltaTime;
if (_angle < target)
_angle = Math.Min(_angle + step, target);
else if (_angle > target)
_angle = Math.Max(_angle - step, target);
transform.localEulerAngles = new Vector3(0f, _angle, 0f);
}
public void Toggle() => _open = !_open;
}

Public fields become per-instance config. Set them in code, or from another script that holds a reference. The Script inspector does not draw a widget per field.

If you want tunable values without editing code each time, expose them through your own key/value store, a config file, or a small settings script. Keep it simple: a public field defaults work for most gameplay.

Use GetComponent<T>() to reach a component or script instance. See Communication.

Previous: Editor setup: VS Code and the engine API.

Next: Scene and game state: managing scenes with SceneManager.