Script works in Studio but does not work in experience

Hello, everything is fine? well, I’ll be straight to the point.
I have a local script in a part, this script checks if the player has a specific item (Players.LocalPlayer.Character:FindFirstChild; It uses Character because when the player is holding an item it becomes there and not in the Backpack). So far everything was fine when I was in the Studio, I published the game update and when I entered the script it didn’t work like it did in the studio


Here is a demo
In-Studio

In-Game


Note that in Studio the Console is empty without any error, in the experience itself it presents an error in the Console

image


This is the Script:

game.Players.LocalPlayer.CharacterAdded:Connect(function()
	while 1 == 1  do
		if game.Players.LocalPlayer.Character:FindFirstChild("Baby") then
			script.Parent.ProximityPrompt.Enabled = true
		else
			script.Parent.ProximityPrompt.Enabled = false
		end
		wait()
	end

end)

By the way, if anyone knows if I can “Improve” this script, such as performance for example :grin:

Ideally, you would use a script located within the tool that is then connected to an Equipped and Unequipped events. However, assuming you don’t want to do that because it requires that you change how you have it set up, you can instead try something like this:

local Player = game.Players.LocalPlayer
local Prompt = script.Parent.ProximityPrompt

Player.CharacterAdded:Connect(function(char)
    char.ChildAdded:Connect(function(child)
         if char.Name == "Baby" then
              Prompt.Enabled = true
         end
    end)

    char.ChildRemoved:Connect(function(char)
         if char.Name == "Baby" then
             Prompt.Enabled = false
         end
    end)
end)

Changing the code to instead use events instead of a while loop may resolve the issue.

2 Likes

Thank you so much, I did some modifications and some tests and realized that this code doesn’t run in a LocalScript, but in a script with the RunContext defined in Client, this was the modified code:

local Player = game.Players.LocalPlayer
local Prompt = script.Parent.ProximityPrompt
wait(Player.Character)
char = Player.Character
char.ChildAdded:Connect(function(child)
	print(child.Name)
	if child.Name == "Baby" then
		Prompt.Enabled = true
	end
end)

char.ChildRemoved:Connect(function(char)
	print(char.Name)
	if char.Name == "Baby" then
			Prompt.Enabled = false
	end
end)

I was reading more about RunContext here on the forum, because I’ve never cared so much about it (and it’s also a relatively new feature) and I saw this post, it explains why the code wasn’t running:

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