Writing a custom Action 2

In the previous tutorial, we created a custom Action that affects the gravity setting of any Rigidbody in our scene. However, it will only work for objects that exist in the scene in Edit mode: it will not work on prefabs that are instantiated during gameplay, nor will it work when used in an ActionList asset file. We will fix this now by using Constant IDs.

Constant IDs are Adventure Creator's way of keeping track of GameObjects between scenes. When the ConstantID script is attached to a GameObject or prefab, it assigns itself a Constant ID number, which we can incorporate into our Action. This will allow our Action to work when asset files are involved.

We'll first declare a new integer, to record the ID number, beneath the existing two:

public GameObject objectToAffect;
public bool newGravityState;
public int constantID;

When we assign a Rigidbody to the Action's GUI, we want to update this ID number reference automatically. Update the ShowGUI function as follows:

override public void ShowGUI ()
	objectToAffect = (GameObject) EditorGUILayout.ObjectField ("Object to affect:", objectToAffect, typeof (GameObject), true);
	newGravityState = EditorGUILayout.Toggle ("New gravity state:", newGravityState);

	constantID = FieldToID (objectToAffect, constantID);
	objectToAffect = IDToField (objectToAffect, constantID, true);

This will cause a Constant ID to be created and recorded if appropriate. Try placing a scene-based GameObject into the GameObject to affect field of an asset-based instance of the Action. You'll see that a Constant ID number will be automatically generated and displayed in the GUI:

Finally, we'll use this Constant ID number to re-assign the objectToAffect variable if appropriate. We can insert a new function, AssignValues, which will be called before an Action is run:

override public void AssignValues ()
  objectToAffect = AssignFile (constantID, objectToAffect);

Our Action is now set up to work with asset files. In the next tutorial, we'll upgrade it further to accept parameters.