How to control multiple motors simultaneously

local speed = script.Parent.VehicleSeat1.DriveGui.spd

local fleet = script.Parent.Parent
local motorL = nil
local motorR = nil

for _,y in ipairs(fleet:GetDescendants("")) do
	if not y:IsA("HingeConstraint") then continue end
	if y.Name == "MotorL" then
		motorL = y
		print(y)
	end
end
for _,v in ipairs(fleet:GetDescendants("")) do
	if not v:IsA("HingeConstraint") then continue end
	if v.Name == "MotorR" then
		motorR = v
		print(v)
	end
end

while true do
	wait()
	motorL.AngularVelocity = speed.Value *1.3
	motorR.AngularVelocity = -speed.Value *1.3
end

This is a control script for a vehicle with multiple motors.
It is trying to find the HingeConstraint named MotorL or MotorR in the model and have it update AngularVelocity every 0.03 seconds.
The speed value is being updated by another script that updates the NumberValue every 0.03 seconds.

The script itself works without error, but only one representative of the multiple motors rotates.

I have tried the method of storing multiple instances in a single variable (creating a table by enclosing them in {}), but it does not work.
Please advise.

You were almost there, but you missed something.

What your code is trying to do is find every motor of the same name, but that would replace the previously found motor, thus you only get the last motor found by the for loops. Better to keep those motors in a table instead:

local motorL = {}
local motorR = {}

for _,y in ipairs(fleet:GetDescendants("")) do
	if not y:IsA("HingeConstraint") then continue end
	if y.Name == "MotorL" then
		motorL[#motorL + 1] = y
		print(y)
	end
end
for _,v in ipairs(fleet:GetDescendants("")) do
	if not v:IsA("HingeConstraint") then continue end
	if v.Name == "MotorR" then
		motorR[#motorR + 1] = v
		print(v)
	end
end

Then, on the while loop, run through all items in the motorL and motorR tables.

while true do
	wait()
	
	for _, v in ipairs(motorL) do
		v.AngularVelocity = speed.Value * 1.3
	end
	for _, v in ipairs(motorR) do
		v.AngularVelocity = -speed.Value * 1.3
	end
end
1 Like

Thanks for the advice!
It worked as expected.
I need to relearn about tables.

1 Like