Help with instance value

So, I’ve made a system in which the player spawns with an instance value attached to them. I have this set up to where the player is able to access certain doors depending on the value they carry. Currently, I’m struggling to acquire the player value through a server script after the player interacts with a button on a computer via a RemoteEvent. While the code I currently have works with the doors in my world- I run into this error:

So I was wondering if it would be better to use an Attribute or something, or is this a simple fix that I’m just simply overlooking? Here is the code from my server script located under ServerScriptService:

-- Get services
local Players = game:GetService("Players")
local ReplicatedStorage = game:GetService("ReplicatedStorage")

-- Get events
local events = ReplicatedStorage.Events
local selectionEvent1 = events.SelectionEvent1

-- Function to assign base value to players upon joining
Players.PlayerAdded:Connect(function(player)
	
	-- Value settings
	local value = Instance.new("NumberValue")
	value.Name = "Selection"
	value.Value = 0
	value.Parent = player
end)

selectionEvent1.OnServerEvent:Connect(function(player)
	
	-- Get selection value
	local selection = player.Character:WaitForChild("Selection")
	selection.Value = 1
	print("Value changed")
end)

You’re trying to get the Selection value in the player’s character when it was parented to the player instance. Is this a mistake? Another thing to note here, there is no need to WaitForChild in a server script because everything in the server is already loaded. Consider using FindFirstChild instead.

1 Like

^ This should be your solution. However, I want to clarify some things:

there is no need to WaitForChild in a server script because everything in the server is already loaded. Consider using FindFirstChild instead.

  1. This only applies to static Instances. In this case, the NumberValue is a dynamically created Instance.
  2. We use FindFirstChild because we want to guarantee that something exists before running code. Otherwise, it can potentially error which is bad practice under remotes.
  3. We don’t want to use WaitForChild without a timeOut argument because it is also bad practice to infinitely yield under remotes, a potential memory leak that will last forever.
2 Likes

Yeah, my mistake. I completely overlooked that.

Thank you. I’ll make sure to apply this.

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