Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

I need some help with Arrays, anyone able to explain what I'm doing wrong?

Asked by 7 years ago
Edited 7 years ago

So, I'm pretty new to Lua and I've been trying to make it to where if a player touches any of the parts that are inside of dayArray, the time will become 12 * 60, and if they touch any of the parts inside of nightArray, the time will become 20 * 60.

However, I'm running into a problem I'm unsure how to resolve. I'm getting an error when I try to run Touched, so I'm wondering what I can do to fix this.

Here's the code:

local dayArray = {game.Workspace.DayParts.Part1, game.Workspace.DayParts.Part2}
local nightArray = {game.Workspace.NightParts.Part1, game.Workspace.NightParts.Part2}

function setDay(part)
    game.Lighting:SetMinutesAfterMidnight(12 * 60)
end

dayArray.Touched:connect(setDay)

function setNight(part)
    game.Lighting:SetMinutesAfterMidnight(20 * 60)
end

nightArray.Touched:connect(setNight)

An explanation of what I'm doing wrong and how to fix it would be nice. Thanks.

1 answer

Log in to vote
1
Answered by 7 years ago

The error you are probably getting is something to the effect of "attempt to index field 'Touched' (a nil value)". The reason for this is, because the array is just a list of parts. In this cause it is a list of parts that when touched will change the time of day. If we want to have it change the time of day when each entry of nightArray is touched. Then we need to iterate through the list and set a .Touched event to each part.

local dayArray = {game.Workspace.DayParts.Part1, game.Workspace.DayParts.Part2}
for i,v in pairs(dayArray) do
    v.Touched:connect(function()
        game.Lighting:SetMinutesAfterMidnight(12 * 60)
    end)
end

Where i is the key in the list and v is the value. In this case the value is a reference to parts in workspace when touched change the time of day. If we apply this to your script it becomes the following.

local dayArray = {game.Workspace.DayParts.Part1, game.Workspace.DayParts.Part2}
local nightArray = {game.Workspace.NightParts.Part1, game.Workspace.NightParts.Part2}

for i,v in pairs(dayArray) do
    v.Touched:connect(function()
        game.Lighting:SetMinutesAfterMidnight(12 * 60)
    end)
end

for i,v in pairs(nightArray) do
    v.Touched:connect(function()
        game.Lighting:SetMinutesAfterMidnight(20 * 60)
    end)
end
0
Why not do "game.Workspace['ASSET']:GetChildren()" instead of doing lines 1 & 2 like that? :P TheeDeathCaster 2368 — 7y
Ad

Answer this question