Skip to main content

RigidBody State Management

States act like custom properties for RigidBodies. These states are similar to how Attributes for Instances work in Roblox Studio. With the help of these states, you are able to keep track of some arbitrary data for multiple RigidBodies. States can be dealt with, using RigidBody:SetState() and RigidBody:GetState().

SetState() method takes in the name of the state which is a string as its first argument and then its value as the second argument. GetState() takes in just the name of the state which you initialized earlier and returns the value for the state.

local body = Engine:Create("RigidBody", { Object = SomeObject, Collidable = true, Anchored = false })

body:SetState("Health", 100)
print(body:GetState("Health")) -- 100

States can help a lot in scenarios where using just a single variable for storing some attribute is impossible. Consider this simple example. You have a lot of RigidBodies. You have a Health attribute for each RigidBody with an initial value of 100. You select a random RigidBody every second and subtract 10 from that RigidBody's health. If the health becomes less than 0, the RigidBody is destroyed. Using just a single variable for this is impossible, since you are said to manage multiple RigidBodies' healths!

Let's lay this down in our code! We start by creating some amount of RigidBodies and initialize their Health as 100. And store the RigidBody in a separate array.

local boxes = {}

for i = 1, 10 do
local box = Engine:Create("RigidBody", {
Object = TheGuiInstance,
Anchored = false,
Collidable = true,
Gravity = Vector2.new(0, 0.2)
})

box:SetState("Health", 100)

table.insert(boxes, box)
end

Next we create the while loop which has a wait time of approximately 1 second. Inside the for loop, we pick a random RigidBody, subtract 10 from its health and destroy it if its health is less than or equal to 0!

while true do
local randomBox = boxes[math.random(1, #boxes)]

local health = randomBox:GetState("Health")
randomBox:SetState("Health", health - 10)

if randomBox:GetState("Health") <= 0 then
randomBox:Destroy()
end

task.wait(1)
end

That's just 1 example of how you can use custom attributes for RigidBodies. You will find more situations like these when working with RigidBodies, if so, States are a great solution!