Instance.new是否可以添加到if语句中



我需要一些关于Roblox脚本的帮助!我是一个初学者,我正在学习如何使用if语句。它们很简单,但是,我想添加一个";例子New("Part"(这里有一个例子:

如果游戏。Lighting.TimeOfDay==";12:00:00";然后local part=Instance.new("part"(结束

这行得通吗?还有一种方法可以让我得到一个手电筒,例如当它变成凌晨3点,这也是可能的吗?

是否可以在if语句中添加Instance.new

最简单的答案是肯定的,这是可能的。但你的问题最好的标题是:

如何在特定时间为玩家提供工具?

只有在精确的秒执行代码时,您的代码才能工作;03:00:00";。因此,因为这种情况不太可能发生,你需要一种反复检查时间的方法。

其他答案建议使用带有wait(seconds)函数的循环来重复检查时间。但这会遇到一个问题,如果等待间隔太大,您可能会从";02:59:59";至";03:00:01";错过了关键时刻;03:00:00";。或者,如果等待间隔太短,当时间为"0"时,您的代码可能会触发多次;03:00:00";。因此,你需要一些东西来确保你的代码只在合适的时候触发一次。我建议使用Lighting.Changed信号。这样,它就会告诉你时间的变化,而不是你问时间是多少。

接下来要记住的是,Lighting.TimeOfDay在你告诉它之前不会改变。所以时间可以像你告诉它的那样快速或缓慢地移动,但你必须编写脚本来改变它。您可以通过设置Lighting.ClockTime或Lighting:SetMinutesAfterMidnight((函数来执行此操作。

最后一件事是找一个手电筒。我建议从工具箱中取出一个工具,并将其作为脚本的子项添加。

这里有一个完整的例子来说明这可能是什么样子。想象一下,这是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)

把这段代码粘贴到localscript//StarterGui为什么我要放一个循环?这样它就可以检查时间何时改变。你需要一个遥控器,这样游戏中的每个玩家都可以看到它,如果你不使用遥控器,它只对一个玩家可见

https://developer.roblox.com/en-us/articles/Remote-Functions-and-Events

delay(0, function()
while true do wait(.1)
if game.Lighting.TimeOfDay == "12:00:00" then
print("Time Changed")
--Put Your Code Here
end
end
end)

最新更新