此代码的目标是在 5 个预设位置之一随机生成一个球“GlowyBall”。当玩家按下按钮时该脚本就会激活。球还需要随机生成 3 种颜色中的一种。该代码在大部分情况下都有效,但在优化该代码时我遇到了困难。我不知道应该甚至可以使用哪种数据类型来替换这些 if 语句。我只是想学习可以采取的不同途径。这段代码需要优化的原因是它每分钟可能被使用数千次,我不希望游戏被这段代码拖住。
...
-- Says that there will be 3 colors
local ColorRange = 3
-- Says that there will be 5 spawn locations
local range = 5
-- Makes the code run continuously
while true do
local ColorNumber = math.random(1, ColorRange)
local Number = math.random(1, range)
-- Chooses the random color
if ColorNumber == 1 then
game.ServerStorage.GlowyBallsSideA.GlowyBallGroup1.Glowyball1.Color = Color3.new(1, 0, 0)
end
if ColorNumber == 2 then
game.ServerStorage.GlowyBallsSideA.GlowyBallGroup1.Glowyball2.Color = Color3.new(0, 1, 0)
end
if ColorNumber == 3 then
game.ServerStorage.GlowyBallsSideA.GlowyBallGroup1.Glowyball3.Color = Color3.new(0, 0, 1)
end
-- Chooses which ball will get cloned
if Number == 1 then
ClonePart = game.ServerStorage.GlowyBallsSideA.GlowyBallGroup1.Glowyball1
end
if Number == 2 then
ClonePart = game.ServerStorage.GlowyBallsSideA.GlowyBallGroup1.Glowyball2
end
if Number == 3 then
ClonePart = game.ServerStorage.GlowyBallsSideA.GlowyBallGroup1.Glowyball3
end
if Number == 4 then
ClonePart = game.ServerStorage.GlowyBallsSideA.GlowyBallGroup1.Glowyball4
end
if Number == 5 then
ClonePart = game.ServerStorage.GlowyBallsSideA.GlowyBallGroup1.Glowyball5
end
wait(.6)
local Clone = ClonePart:Clone()
script.Parent.ClickDetector.MouseClick:connect(function()
Clone.Parent = game.Workspace
Clone.Anchored = false
end)
end
...
我对整个编程还很陌生,所以请随意教我一些东西,谢谢。
最佳答案
Roblox 中的实例可以通过几种不同的方式访问;最常见的是点符号(例如game.Workspace.Part
)。还可以访问表中的项目等实例(例如game["Workspace"]["Part"]
)。当访问名称中包含空格的实例或在访问字符串之前在字符串的开头/结尾添加某些内容时,这非常有用。
用于选择克隆哪个球的 if 语句可以简化为以下内容:
-- Chooses which ball will get cloned
ClonePart = game.ServerStorage.GlowyBallsSideA.GlowyBallGroup1["Glowyball" .. Number] -- Add Number to the end of "Glowyball" before accessing it
选择随机颜色也可以实现同样的效果,并且用多个 if 语句替换一个 if-elseif 语句可以使代码更具可读性。
-- Chooses the random color
local Glowyball = game.ServerStorage.GlowyBallsSideA.GlowyBallGroup1["Glowyball" .. ColorNumber]
if ColorNumber == 1 then
Glowyball.Color = Color3.new(1, 0, 0)
elseif ColorNumber == 2 then
Glowyball.Color = Color3.new(0, 1, 0)
elseif ColorNumber == 3 then
Glowyball.Color = Color3.new(0, 0, 1)
end
关于optimization - 如何在 Roblox Studio 中优化 If 语句的过度使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73178823/