Object Scripts

Object scripts control the complex behaviour of an object. For details on scripting see the C4Script documentation.


For every object, the engine calls the function Initialize in the object script when it is created and completed.
func Initialize()
An object with this script will be given a rock right after it has been created. The Initialize function is called only when the object has reached full size (a building only when its construction has been completed and a living being only when it is fully grown).


An active object can also define activity script calls in its ActMap. The defined StartCall is made whenever an action begins (or repeats), an EndCall is made at the end of each activity. PhaseCall is called at each animation phase step and should only be used for very short animations. The call frequency of PhaseCalls is determined by the speed of the animation.


An object script can also include the functionality of another script.
#include Clonk
At this position the complete script of the specified object definition (that of the clonk, in this case) is inserted, including all scripts that that script includes or got via #appendto. The only exception is that every script is included only once, so including both the Clonk script and a script that is included by the Clonk script doesn't include that script twice. Other Obviously, the included definition must be valid and loaded. Declared functions can be overloaded by functions of the same name that occur later in the script. Also see inherited().

Interaction from other scripts

Other scripts can call functions of an object obj with the -> and ->~ operators.
var obj = CreateObject(Flint); obj->Hit();

Object calls made by the engine

The engine calls the following functions is objects at the given time.
Function Parameter Description
Definition Called in definition context after all definitions have been loaded and before definition properties are frozen. Use this callback to initialize complex definition properties such as EditorProps or dependencies between definitions. Definition() callbacks are performed in descending order of the DefinitionPriority property or 0 if that property is not defined.
Initialize When the object is completed (Con >= 100).
Construction object by_object When the object is created. The parameter is a pointer to the object the script of which has created this object. Also see Construction
Destruction When the object is removed.
EditorInitialize Called after Construction and Initialize when the object is placed in the editor.
Hit When the object collides with the landscape or is collected at high velocity (>=15).
Hit2 Like Hit, with speeds >= 20 (see OCF_HitSpeed2).
Hit3 Like Hit, with speeds >= 60 (see OCF_HitSpeed3).
Grab object target, bool grab When the object grabs or lets go of another object.
Grabbed object by_object, bool grab When the object is grabbed or let go by another object.
Get object target When the object takes another object from a container.
Put When the object puts another object into a container.
DigOutObject object obj When the object dug out another object that was stuck in solid material or when a new object is created from material during digging.
DugOut object object_by When the object was spawned from dug out material. The object might get removed afterwards if the material has Dig2ObjectCollect=2.
Damage int change, int cause, int by_player When the object is damaged. See Fx*Damagefor cause values.
DeepBreath When a living being surfaces after having used up more than half of its breath.
Incineration int by_player When the object is incinerated. Notice: with objects changing their definition via BurnTo, this call is made to the burned version!
IncinerationEx int by_player When the object is incinerated in and immediately extinguished by a surrounding liquid. Otherwise as Incineration.
Death When a living being dies.
Activate object by_object Activation by double dig. Only applies to collected items or directly controlled crew objects. Called after internal handling of the double dig command has been completed (e.g. chopping of trees etc.)
Contact_ When the object collides with the landscape. See CNAT - Contact Attachment.
Control_ object by_object When the object is controlled from the outside. See Control Functions.
Contained_ object by_object When the object is controlled from the inside. See Control Functions.
ControlCommand string command, object target, int x, int y, object target2, int data, object command_object When the object has received a command to be independently executed. See Control functions.
ControlCommandFinished string command, object target, int x, int y, object target2, any Data When the object has completed a command or execution of a command has failed.
ControlTransfer object obj, int x, int y When an object (obj) using the internal pathfinding algorithm is trying to pass the transfer zone of this object on its way to point x/y. The transfer function can then help the object along by giving special script commands and returning true. Also see SetTransferZone().
OnSynchronized When an object is loaded from a savegame or network synchronization is performed. Objects with a transfer zone should reset the zone in this call. Also see SetTransferZone().
IsFulfilled Only in game goal objects. A return value true indicates that this goal is fulfilled.
ControlContents id target When a new inventory object is selected. See Control Functions.
Selection object container When the object is selected in an inventory change. If you are processing this event, the function should play its own selection sound.
CatchBlow int level, object by When the object is hit or punched by another object.
QueryCatchBlow object by Called before the object is hit or punched by another object. By returning true, QueryCatchBlow can reject physical blows.
OnLineBreak int cause When a line object is broken. cause: 0 by movement, 1 because of a missing or incomplete target object.
OnLineChange int cause When a line object is changed, that is when one of it vertices changed its position.
AttachTargetLost When the object is in an ATTACH action and has lost its action target. At this time, the object's action has already been reset.
CrewSelection bool deselect, bool cursor_only When crew selection is changed. cursor_only specifies whether only that crew member has been selected which is also the cursor.
GetObject2Drop object for_collection_of_object Called to determine the least needed inventory object when a clonk tries to collect a new object and his inventory is full. The function should return the object to be dropped to gain space, or nil if none.
OnMenuSelection int index, object menu_object When an object menu entry is selected.
CalcValue object in_base, int for_player Calculates the value of an object. Also see GetValue().
CalcDefValue object in_base, int for_player Calculates the value of an object type available to buy. Also see GetValue().
CalcBuyValue id item, int value Returns the buying price of the object type.
CalcSellValue object obj, int object_value Returns the selling price of the object type.
LiftTop When an object with LIFT action lifts its action target to the height specified in its DefCore or above.
Stuck When the action target of the object's PUSH or LIFT action is stuck.
GrabLost When the action target of the object's PUSH or PULL action is lost.
Collection object obj, bool put When the object has collected another object (obj) (by ingame collection or grabbing and getting).
Collection2 object obj When the object has collected another object (obj) (in all cases, even in script controlled collection or entering).
ContentsDestruction object destroyed When an object contained in the object has been destroyed/removed. The object still exists when the callback is called, but will be destroyed afterwards.
Departure object container When this object has left another object (container).
Ejection object obj When another object (obj) has left the contents of this object (also see script command Exit).
Entrance object container When the object has entered another object (container).
ActivateEntrance object by_object When another object is trying to enter this object through the entrance.
RejectCollect id def, object obj Called before Collection. If RejectCollect returns true, the collection of the other object is prevented.
RejectEntrance object into_object Called before Entrance. If RejectEntrance returns true, then entrance of the other object is prevented.
InitializePlayer int player Called in game goals, rules, or environment objects after the joining of a new player and before the corresponding call in the scenario script.
SellTo int by_player When the object is sold. Should return nil or the id of the object type which is actually added to the player's homebase material.
Sale int by_player When the object is sold.
Purchase int by_player, object buy_object When the object is bought.
Recruitment int player When the objet is added to the crew of a player.
RejectTeamSwitch int player, int new_team Callback in game goal, rule, and environment objects and in the scenario script. If RejectTeamSwitch returns true, the team switch of a player can be prevented (see SetPlayerTeam).
OnTeamSwitch int player, int new_team, int old_team Callback in game goal, rule, and environment objects and in the scenario script. Called when a player has successfully switch from old_team to new_team (see SetPlayerTeam).
OnCompletionChange int old_con, int new_con Callback in when the completion of the object has changed (see GetCon, DoCon and SetCon).
EditCursorMoved int old_x, int old_y When object is moved in editor. Callback is also done when moved in non-network pause mode. old_x, old_y contains object position before movement.
SaveScenarioObject proplist props Called when scenario is saved from the editor. Object should write creation of itself and properties to the buffer props. Return true if the object should be saved and false if saving of this object should be omitted. See Scenario saving.

Scenario saving

When the user chooses the "Save Scenario" option from the editor menu, the engine calls a global function SaveScenarioObjects defined in System.ocg/SaveScenario.c. This function writes all objects to the Objects.c file in their current state. The function stores all objects except the crew of currently joined human players and objects of a type that starts with GUI_. By default, objects are recreated using a call to CreateObject followed by setting a number of default properties like position, rotation, speed, action, if they are not in their default state.
For most object, the default saving method should be fine. However, it is possible to override the SaveScenarioObject callback to control how objects are created and which properties are set.
For example if a switch wants to save its target which is stored in a local variable called "target", the switch definition can override the callback:
local target;

func SetTarget(object new_target) { target = new_target; return true; }

func SaveScenarioObject(props)
	if (!inherited(props, ...)) return false;
	if (target) props->AddCall("Target", this, "SetTarget", target);
	return true;
As a result, the generated Objects.c file will include the call to SetTarget if the switch is saved. Dependent objects should always either be passed to the AddCall function or stored as a string from the MakeScenarioSaveName function. If this is done, that object is marked as a dependency. The saving mechanism will ensure that any object this object depends on will be created before. In case of circular dependencies, the object property setting script is detached from object creation script.
If an object should not be saved in scenarios - for example, because it is just the helper of another object - the SaveScenarioObject callback should be overloaded to return false.
The object creation procedure can also be adjusted. For example, the waterfall object (defined in Objects.ocd/Environment.ocd/Waterfall.ocd) is created using the global functions CreateWaterfall and CreateLiquidDrain, which create a Waterfall object and attach an effect to it. To generate the creation functions from the effects, the waterfall overrides SaveScenarioObject:
func SaveScenarioObject(props)
	if (!inherited(props, ...)) return false;
	var fx_waterfall = GetEffect("IntWaterfall", this);
	if (fx_waterfall)
		props->Add(SAVEOBJ_Creation, "CreateWaterfall(%d,%d,%d,%v)",fx_waterfall.X, fx_waterfall.Y, fx_waterfall.Strength, fx_waterfall.Material);
	return true;
The call to RemoveCreation removes the existing object creation using CreateObject.
If you need access to one of the objects created in the editor, you can set its "StaticSaveVar" property to the name of a static variable. The InitializeObjects() function will then save the object in that variable.
The following table lists standard properties that are saved if their value is different from the default and if it is not removed using a props->Remove call.
Property name Default value Description
Alive true Category C4D_Living only: If object is not alive, a call to SetKill is stored. See GetAlive and Kill.
Action this.DefaultAction Action as retrieved using GetAction and set using SetAction. Includes ActionTargets. Not stored by default but only if SaveScenarioObjectAction is called.
Phase 0 Action phase (see GetPhase and SetPhase). Not stored by default but only if SaveScenarioObjectAction is called.
Dir DIR_Left Animation direction (see GetDir and SetDir)
ComDir COMD_Stop Commanded movement direction (see GetComDir and SetComDir)
Con 100 Construction percentage, i.e. object size (see GetCon and SetCon)
Category GetID()->GetCategory() Object category (see GetCategory and SetCategory)
R 0 Rotation (see GetR and SetR)
XDir 0 Horizontal speed (see GetXDir and SetXDir)
YDir 0 Vertical speed (see GetYDir and SetYDir). Vertical speed is not saved it is very small and the object touches the ground to avoid saving of speed on idle objects.
RDir 0 Rotation speed (see GetRDir and SetRDir)
Color 0, 0xffffffff Object color of ColorByOwner-surfaces (see GetColo and SetColor)
ClrModulation 0, 0xffffffff Object color modulation of all surfaces (see GetClrModulation and SetClrModulation)
BlitMode 0 Object drawing mode (see GetObjectBlitMode and SetObjectBlitMode)
MeshMaterial GetID()->GetMeshMaterial() Custom assignments of mesh materials (see GetMeshMaterial and SetMeshMaterial)
Name GetID()->GetName() Object name (see GetName and SetName)
MaxEnergy GetID().MaxEnergy Maximum energy (see Properties)
Energy GetID().MaxEnergy/1000 Current energy level (see GetEnergy and DoEnergy)
Visibility VIS_All Object visibility (see Properties)
Plane GetID().Plane Object plane, i.e. z-order (see Properties)
Position Object position. This is only set if the object has a rotation and could not be created directly at the correct offset (see SetPosition)
Command None Stores only the topmost command of the chain (see GetCommand and SetCommand)
Fire Fire effect.
Properties published to the editor as EditorProps can also be saved automatically by setting the Save property of the EditorProp to a string that serves as an identifier so saved properties can be removed by derived definitions. These properties are atuomatically saved if they are different from their default value. E.g.:
/* Define two properties that can be set in the editor */
// foo is a property with a setter function
local foo = 42;
public func SetFoo(new_foo) { foo = new_foo; return true; }

// bar is just a property without setter
local bar = 23;

local EditorProps = {
  foo = { Type="int", Set="SetFoo", Save="Foo" }; // saved as object->SetFoo(value); unless foo is 42.
  bar = { Type="int", Save="Bar"; } // saved as object.bar = value; unless bar is 23.
By default, effects are not saved in scenarios. To force saving of an effect, define the Fx*SaveScen callback. For example, the fire effect saves itself like this:
global func FxFireSaveScen(object obj, proplist fx, proplist props)
	// this is burning. Save incineration to scenario.
	props->AddCall("Fire", obj, "Incinerate", fx.strength, fx.caused_by, fx.blasted, fx.incinerating_object);
	return true;
obj and fx refer to the object and effect proplist as for any effect call. save_name is the variable name of the effected object and is unset for global effects.

Scenario saving reference

The following functions are available to call on the "props" parameter passed to SaveScenarioObject callbacks:


bool AddCall(string id, object target, string function, any par1, any par2, ...);
Adds a new call of format target->Function(par1, par2, ...) to the stored object script. Object parameters may be passed as is; strings must be quoted explicitely.
The id parameter is an identifier which can be used by derived objects to remove the property again.


bool AddCall(string id, string script, any par1, any par2, ...);
Adds a custom script snippet of any format. script may contain format characters and parameters are formatted into the string using Format().


int Remove(string id);
Remove all strings added previously using AddCall or Add with the given ID. Can also be used to remove default properties. Returns number of script lines removed.


bool RemoveCreation();
Remove all strings added previously using with IDs SAVEOBJ_Creation or SAVEOBJ_ContentsCreation.


bool Clear();
Remove all creation and property setting strings.
sulai, 2003-11
matthes, 2004-07
Clonkonaut, 2008-04
Sven2, 2013-12