Attempt to index nil with Color (It suddenly got nil in the function)

I’ve been struggling with this code for a while please help.

When I print self.Lamp in .new() section it works perfectly but when I tried in :Ignite() function the output become nil

--// Initialisation

local CollectionService = game:GetService("CollectionService");

local Street_Lamp_Class = {}
Street_Lamp_Class.__index = Street_Lamp_Class

--// Functions

function Street_Lamp_Class.new(Object)

    local self = setmetatable({}, Street_Lamp_Class)
    self.Object = Object
    self.PrimaryPart = self.Object.PrimaryPart

    self.OriginalColour = Color3.fromRGB(72, 69, 66)
    self.IgnitedColour = Color3.fromRGB(160, 143, 109)

    self.Lamp = self.PrimaryPart
    self.SurfaceLight = self.Lamp.Attachment.SurfaceLight
    self.SurfaceLight.Shadows = false
    self.Sound = self.Lamp:FindFirstChild("Light_buzz")

    print(self.Lamp) --// Lamp

end

function Street_Lamp_Class:Ignite()

    warn(self.Lamp) --// nil

    self.Lamp.Color = self.IgnitedColour
    self.SurfaceLight.Enabled = true

    self.Sound:Play()

end

return Street_Lamp_Class




property existence check

Please send help…

Haven’t dealt with OOP much, BUT I think you may need to return self in the .new() function, right?
(This may be completely wrong, but it’s an attempt!
(I repeat - this may be (probably will be) completely wrong)


You are also setting the local self instead of just self, which may be affecting it

1 Like

Thank you for your reply. Sadly the solutions you have provided did not fix the problem but I’m really appreciate the attempts. And yeah thank you again, I forgot the return self.


Global self is only used in the enclosing function ‘new’

You need to call :Ignite() on what is returned with Lamp_Class.new(), not the module itself.

Something like this could work:

for _, v in CollectionService:GetTagged("Lamp") do
    Lamp_Class.new(v):Ignite()
end

Or you store all the new lamps in a new array and then loop through that calling Ignite()

local myLamps = {}

for _, v in CollectionService:GetTagged("Lamp") do
    table.insert(myLamps, Lamp_Class.new(v))
end

for _, v in myLamps do
    v:Ignite()
end
1 Like

Thank you so much!!! It does work!

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.