Instance.new 是否可以添加到 if 语句中
最简单的答案是肯定的,有可能。但您的问题的更好标题是:
我如何在特定时间给玩家一个工具?
并且您的代码只有在时间为“03:00:00”的准确秒执行时才能工作。因此,由于这种情况不太可能发生,因此您需要一种方法来反复检查时间。
其他答案建议使用带有wait(seconds) 函数的循环作为重复检查时间的方法。但这会遇到一个问题,如果等待间隔太大,您可能会从“02:59:59”转到“03:00:01”而错过恰好是“03:00:00”的关键时刻.或者,如果等待间隔太短,您的代码可能会在时间为“03:00:00”时触发多次。所以你需要一些东西来确保你的代码只在适当的时候触发一次。我建议改用Lighting.Changed signal。这样一来,它就不会问你现在几点了,它会在时间变化时告诉你。
接下来要记住的是,Lighting.TimeOfDay 在您告诉它之前不会改变。因此,时间可以按照您所说的那样快或慢地移动,但您必须编写脚本来改变它。您可以通过设置Lighting.ClockTime 或Lighting:SetMinutesAfterMidnight() function. 来做到这一点
最后一步是找到一个手电筒。我建议从工具箱中取出Tools 之一并将其添加为Script 的子项。
这里有一个完整的例子。想象这是ServerScriptService 中的一个脚本,它有一个手电筒工具作为脚本的子级。
local Lighting = game:GetService("Lighting")
local Players = game:GetService("Players")
-- 1) grab a reference to the flashlight Tool
local flashlightTool = script.Flashlight
-- 2) create a different thread to handle time changes
spawn(function()
-- round the number to avoid floating point math issues
local oneSecond = tonumber(string.format("%.4f", 1.0 / 3600.0))
-- progress the time of day
while true do
-- to speed up time, multiply oneSecond by 2, 3, 4, 5, 6, 10, or any factor of 60
-- this will ensure that minutes are still hit on time
Lighting.ClockTime += oneSecond
wait(1.0)
end
end)
-- 3) listen for when the time of day changes
Lighting.Changed:Connect(function(propertyName)
if propertyName == "TimeOfDay" then
--print("Time of Day changed : ", Lighting.TimeOfDay)
if Lighting.TimeOfDay == "03:00:00" then
-- give everyone a flashlight
warn("IT'S 3 AM")
local players = Players:GetPlayers()
for i, player in ipairs(players) do
-- check if they already have one, and escape if they do
if player.Backpack:FindFirstChild(flashlightTool.Name) then
continue
end
local flashlight = flashlightTool:Clone()
flashlight.Parent = player.Backpack
end
end
end
end)