I am trying to create a flashlight script that drains the flashlight’s battery when it is equipped. The Modulescript stops at line 6, giving the error "Attempt to index nil with ‘GetDescendants’. I tried defining the tool as a child of starterpack, but the script still doesn’t work.
ModuleScript:
local Flashlight = {}
local Tool = game.StarterPack.ShakeTool
function Flashlight:DrainBattery(Tool)
local Lights = {} -- Create table to store lights in so their brightness can be changed at the same time
for i, child in pairs(Tool:GetDescendants()) do -- The issue
if child:IsA("SpotLight") then -- Finds the lights
print("Found a light, Adding to table.")
table.insert(child, Lights)
end
end
local Battery = 100
if Battery > 0 then
repeat
Battery -= 1
task.wait(0.5)
for i, light in pairs(Lights) do
light.Brightness = Battery / 100
print(Battery)
end
until Battery == 0 or Tool.Unequipped
end
end
return Flashlight
Server Script:
local Item = script.Parent
local DrainBattery = Shakelight.DrainBattery
Item.Equipped:Connect(function()
DrainBattery(Item)
end)
Are these scripts the child of the tool or somewhere else? If somewhere else then a tool would be in the Player’s backpack upon running the game, if they are a child of said tool then you can use script.Parent.
Yes, this is exactly what I want. I see that in the module script you assigned “Tool” twice as well. Maybe remove the first tool variable? (I just noticed this right now)
So basically:
local Flashlight = {}
-- local Tool = game.StarterPack.ShakeTool Removed this
function Flashlight:DrainBattery(Tool) -- Tool already assigned?
local Lights = {} -- Create table to store lights in so their brightness can be changed at the same time
for i, child in pairs(Tool:GetDescendants()) do -- The issue
if child:IsA("SpotLight") then -- Finds the lights
print("Found a light, Adding to table.")
table.insert(child, Lights)
end
end
local Battery = 100
if Battery > 0 then
repeat
Battery -= 1
task.wait(0.5)
for i, light in pairs(Lights) do
light.Brightness = Battery / 100
print(Battery)
end
until Battery == 0 or Tool.Unequipped
end
end
return Flashlight
local Flashlight = {}
local Tool = script.Parent.Parent -- using that
function Flashlight:DrainBattery() -- Removed "Tool"
local Lights = {} -- Create table to store lights in so their brightness can be changed at the same time
for i, child in pairs(Tool:GetDescendants()) do -- The issue
if child:IsA("SpotLight") then -- Finds the lights
print("Found a light, Adding to table.")
table.insert(child, Lights)
end
end
local Battery = 100
if Battery > 0 then
repeat
Battery -= 1
task.wait(0.5)
for i, light in pairs(Lights) do
light.Brightness = Battery / 100
print(Battery)
end
until Battery == 0 or Tool.Unequipped
end
end
return Flashlight