Component fields and the Properties window
You can use Lua scripts to create components with modifiable properties and values, enabling convenient customization straight from the Properties window, much like other built-in components. Upon creating a new component, two Lua scripts are automatically generated: a .lua script for implementing runtime logic and a .editor.lua script for defining and managing the component's editable fields.
Let's use the default Move Component in the .editor.lua as an example. It defines a field for move speed in the Properties window.
local fieldDefs = {
---Define your Property window fields here.
{
name = "moveSpeed",
type = "Vector3",
label = "Move Speed",
hint = "Specify the move speed of the object",
default = Vector3(1, 0, 0)
}
}
script.DefineFields(fieldDefs)
With this setup, each YahahaObject with the component can have a unique value for the move speed field. In the .lua script, you can access the field value using script.fields.fieldName. For example, the Move Component can update the YahahaObject's position based on the specified speed:
script.OnUpdate(function (deltaTime)
---Implement the component's update logic here. This function will be called once per frame.
script.gameObject.transform.position = script.gameObject.transform.position + script.fields.moveSpeed * deltaTime
end)
In the .lua script, you can get the field value by script.fields.fieldName. For example, the Move Component can move the game object with the specified speed.
Script name to component name conversion
The Properties window converts your script name to a label in certain ways. For example, the script component name in the example has been converted from movespeed to Movespeed. The rules are as follows:
- Capitalize the first letter of each word
- Add a space between lowercase and uppercase characters
- Replace "_" with space
- Remove any excess spaces between words, leaving only one space