I have a script that I want to do the following:
Player stands on a part. A ScreenGui called 'MapGui' is enabled, so that the player can view the Gui. A sound is then played, which is named 'Sound', and is a child to 'MapGui'. The player is then teleported to a random co-ordinate in a specific area.
However, when I attempt to test the script, I get the error 'Attempt to index a nil value', on the 'gui' variable in my script. Anyone know how I can fix this?
Code:
part = script.Parent part.Touched:connect(function(hit) if (hit.Parent:FindFirstChild("Humanoid") ~= nil) then local player = game.Players:FindFirstChild(hit.Parent.Name) local gui = player.PlayerGui:FindFirstChild("MapGui") gui.Enabled = true gui:FindFirstChild("Sound"):Play() local xCor = math.random(-34, 0) local zCor = math.random(28.5,63.5) hit.Parent.Torso.CFrame = CFrame.new(xCor,1.5,zCor) end end)
This is not working because you used a Script to handle this. Use a LocalScript to make the Gui visible to the player. Put a Remote Event in ReplicatedStorage, and put this code in a LocalScript. As a bonus, this works for FE.
local show = Instance.new("RemoteEvent",game:GetService("ReplicatedStorage")) show.Name = "ShowMap" show.OnClientEvent:Connect(function(enabled) local pgui = game:GetService("Players").LocalPlayer:WaitForChild("PlayerGui") pgui:FindFirstChild("MapGui").Enabled = enabled pgui.MapGui.Sound:Play() end)
Now, inside the Script, (Not local) do your code, and please do not use :connect it is deprecated, use :Connect. Using deprecated code can cause problems.
local part = script.Parent part.Touched:Connect(function(part) -- Don't use :connect use :Connect if part.Parent:FindFirstChild"Humanoid" then -- Don't wrap your if statements in () local plr = game:GetService("Players"):GetPlayerFromCharacter(part.Parent) if plr then local show = game:GetService("ReplicatedStorage"):WaitForChild("ShowMap") show:FireClient(plr, true) -- Specify the player first, then the arguments. I had a parameter, here is the argument. end)