I recently made a functional tower defense game with no lobby and just direct gameplay.
But thats not the issue.
I want to create a script to give a random color to an enemy when it spawns. This only works when i use while true do loop, and im aware that its quite horrible for performance. Is there anything better I can use? If so, please let me know. All help and inputs are appreciated.
Thank you in advance.
Heres the code.
local killbot = workspace:WaitForChild("Mobs"):WaitForChild("Killbot")
while true do
if killbot then
if killbot.BINGBONG:IsA("BasePart") then
killbot.BINGBONG.Color = Color3.fromRGB(math.random(0,255), math.random(0,255), math.random(0,255))
end
end
task.wait(1)
end
Using the if statement without the While true do loop only executes the code once (not what i need)
Well, I might be wrong but I noticed a possibility of an infinite loop… so I’d say the script should have a slight change so it only runs when a new enemy is added
local mobsFolder = workspace:WaitForChild("Mobs")
mobsFolder.ChildAdded:Connect(function(child)
if child.Name == "Killbot" and child:FindFirstChild("BINGBONG") and child.BINGBONG:IsA("BasePart") then
child.BINGBONG.Color = Color3.fromRGB(math.random(0,255), math.random(0,255), math.random(0,255))
end
end)
Tags are metadata (data about data) for Instances,
you can give any Instance a tag by using Instance:AddTag(tag: string).
This can be useful if you have a game that contains different types of Zombies for example, where you can give each Zombie Instance a Tag “Zombie” and rename them to whatever you want, eg. “BigZombie” or “ZombieBoss”.
You can loop through Instances in a folder or workspace and check if they are a Zombie with Instance:HasTag(tag) . It’s a great practise to get better at coding and it can bring some structure to your game.
You can also use Collection Service, which is better because it keeps all Instances with a certain tag in one place and accessable at any time without needing extra tables.