【发布时间】:2016-07-26 03:54:21
【问题描述】:
-- 这是 Roblox 自己编写的一些代码:
-- Setup table that we will return to scripts that require the ModuleScript.
local PlayerStatManager = {}
-- Table to hold all of the player information for the current session.
local sessionData = {}
-- Function the other scripts in our game can call to change a player's stats. This
-- function is stored in the returned table so external scripts can use it.
function PlayerStatManager:ChangeStat(player, statName, changeValue)
sessionData[player][statName] = sessionData[player][statName] + changeValue
end
-- Function to add player to the sessionData table.
local function setupPlayerData(player)
sessionData[player] = {Money = 0, Experience = 0}
end
-- Bind setupPlayerData to PlayerAdded to call it when player joins.
game.Players.PlayerAdded:connect(setupPlayerData)
-- Return the PlayerStatManager table to external scripts can access it.
return PlayerStatManager
--------------------------------------------------------------------------------
-- Require ModuleScript so we can change player stats
local PlayerStatManager = require(game.ServerStorage.PlayerStatManager)
-- After player joins we'll periodically give the player money and experience
game.Players.PlayerAdded:connect(function(player)
while wait(2) do
PlayerStatManager:ChangeStat(player, 'Money', 5)
PlayerStatManager:ChangeStat(player, 'Experience', 1)
end
end)
当我运行这两个脚本时,它运行完美,在ChangeStat 函数中添加了print(sessionData[player][statName]),但是当我删除模块脚本中的game.Players.PlayerAdded:connect(setupPlayerData) 部分时,它停止工作。我虽然模块脚本在没有被调用的情况下不会执行代码,如果是这种情况,game.Players.PlayerAdded:connect(setupPlayerData) 部分不应该是延迟而不是功能,因为玩家已经添加,因此它不会触发?
【问题讨论】:
-
您删除了
:connect(setupPlayerData)行,发生了什么?究竟是什么停止了工作?你有没有得到任何错误?否则,我希望对ChangeStat的调用会引发错误,因为它们尝试修改的表将不会被正确创建。 -
那么当新玩家进入时模块将运行而无需调用设置函数?
-
模块代码(函数外等)在模块加载时运行。这就是它设置回调函数以在其他事件发生时调用的方式。您删除了为
PlayerAdded事件设置的回调设置,该事件设置了添加到PlayerAdded事件的 other 回调需要正常工作的内部数据结构。从本质上讲,您从三步流程中删除了第一步,因此您打破了第二步和第三步。 -
这是有用的信息,谢谢。