Title, im trynna make a script where, if youre the first one to touched the island, it becomes yours.
but on line 12 it says Attempt to index nil with parent, and i dont know why.
i know what the error means, but i dont know how to fix it, or why the error occured
also island.Occupant.Value is a StringValue
script:
local plr = game:GetService("Players"):FindFirstChild("LocalPlayer")
local islands = game:GetService("Workspace"):WaitForChild("Islands"):WaitForChild("Islands")
local island = islands:GetChildren()
for i, island in pairs(islands:GetChildren()) do
local freeIslands = {}
if island.Occupant.Value == nil then
table.insert(freeIslands, island)
end
end
local function touched(otherPart)
local partParent = otherPart.Parent
local humanoid = partParent:FindFirstChild("Humanoid")
if humanoid then
island.Occupant.Value = tostring(plr.Name)
else
return
end
end
island.Touched:Connect(touched())
This should be your issue. When you’re connecting it to an event, you aren’t supposed to call the function touched(), rather, you are supposed to only pass in the function itself, touched.
Try changing that to: island.Touched:Connect(touched).
Well yeah, it makes sense. You’re running .Touched on a table instead of a part. You need to iterate over every island first and then use the .Touched function.
Try switching island.Touched:Connect(touched) to this:
for i,v in pairs(island) do
v.Touched:Connect(touched)
end
I believe there also is an issue on this line.
This is likely suppose to be otherPart.Occupant.Value = tostring(plr.Name), since island is the table of all the islands as you’ve defined above.
But occupant is a stringvalue and since other part is supposed to be humanoid, there is no occupant in humanoid. occupant is in Island1Island2Island3 etc, as i showed earlier.
Oh, my bad. Perhaps it would be best to do this instead:
for i,v in pairs(island) do
v.Touched:Connect(function(otherPart)
local partParent = otherPart.Parent
local humanoid = partParent:FindFirstChild("Humanoid")
if humanoid then
v.Occupant.Value = tostring(plr.Name)
else
return
end
end)
end
By the way, I would suggest you do this in a Server Script instead of a LocalScript. This is because the changes you are doing right now will only affect you, instead of all the players in the game. The correct approach for this would be to insert a Script in the Workspace with the final code of:
local islands = game:GetService("Workspace").Islands.Islands
local island = islands:GetChildren()
local freeIslands = {}
for i, island in pairs(islands:GetChildren()) do
if island.Occupant.Value == nil then
table.insert(freeIslands, island)
end
end
for i,v in pairs(island) do
v.Touched:Connect(function(otherPart)
local character = otherPart:FindFirstAncestorOfClass("Model")
if character then
local humanoid = character:FindFirstChildOfClass("Humanoid")
if humanoid then
local plr = game.Players:GetPlayerFromCharacter(character);
v.Occupant.Value = plr.Name
end
end
end)
end