偵聽角色

遊戲的目標試看看哪個玩家能活得最久,因此每次玩家死亡之後就需要將他的分數歸零

你將需要從玩家取得 Character 模型以偵測玩家是否死亡。這個模型只在玩家物件載入時被加到遊戲中,而且你能夠使用 [CharacterAdded](<https://developer.roblox.com/en-us/api-reference/event/Player/CharacterAdded>) 事件來偵聽角色是否準備好使用了

-- SetupPoints.lua

local Players = game:GetService("Players")

local function onCharacterAdded(character, player)

end

local function onPlayerAdded(player)
	local leaderstats = Instance.new("Folder")
end

儘管你加入 player 到 onCharacterAdded 函式的參數列中,真正的 CharacterAdded 事件只回傳 character,而不包含 player

-- SetupPoints.lua

local function onPlayerAdded(player)
	local leaderstats = Instance.new("Folder")	
	leaderstats.Name = "leaderstats"	
	leaderstats.Parent = playerlocal 
	points = Instance.new("IntValue")	
	points.Name = "Points"	
	points.Value = 0	
	points.Parent = leaderstats	

	-- 想辦法從有的地方傳入
	player.CharacterAdded:Connect(function(character)		
		onCharacterAdded(character, player)
	end)
end

處理玩家的死亡

當玩家死亡,他們的 [Humanoid](<https://developer.roblox.com/en-us/api-reference/class/Humanoid>) 會自動發送一個 [Died](<https://developer.roblox.com/en-us/api-reference/event/Humanoid/Died>) 事件。你能夠使用這個事件來尋找何時要重置他們的分數

你可以在 Character 模型找到 Humanoid ,但模型的內容只有在玩家生成時才會組裝完成。為了確保你的程式會等到 Humanoid 物件載入後才安然執行,使用 [WaitForChild](<https://developer.roblox.com/en-us/api-reference/function/Instance/WaitForChild>) 函式,你可以在任何上層物件呼叫它,傳入你所尋找的子物件的名稱字串

-- SetupPoints.lua

local Players = game:GetService("Players")

local function onCharacterAdded(character, player)
	local humanoid = character:WaitForChild("Humanoid") --確保等到 Humanoid 載入後才執行
end

你需要用來連接 Died 事件的函式非常短,而且只需用到一次,所以我們選擇再一次使用匿名函式

  1. 連接一個新匿名函式到 Humanoid 的 Died 事件
  2. 在匿名函式內,建立一個名為 points 的變數,用來儲存玩家的 Points 物件
  3. 設定 points 名為 Value 的屬性值為 0
-- SetupPoints.lua

local Players = game:GetService("Players")

local function onCharacterAdded(character, player)
	local humanoid = character:WaitForChild("Humanoid") 
	 
	-- 因為這個被連接的方法只會用到一次,所以改用匿名方式處理   
	humanoid.Died:Connect(function()
		local points = player.leaderstats.Points    	
		points.Value = 0 -- 將分數歸零
	end)
end