当任何具有相同名称的对象被触摸时,如何运行代码



所以我正试图在Roblox上开发一款小型的硬币收集游戏,而且我对脚本还很陌生。基本上,每隔0.25-1.5秒,就会有一小部分从(-254, 2, -255)(基板的一个角(克隆到(254, 2, 255)(相反的角(。这很有效,但我试图在workspace中名为coin的每个对象上循环,当其中一个对象被触摸时,运行代码(目前我只是试图销毁该对象,但可能只是更新Coins的leaderstat(。它没有给我任何错误,只是不起作用。我也在网上到处找,什么也找不到。

ServerScriptStorage中的代码(生成多维数据集并且已经工作,但显示它以寻求帮助。(:

local runservice = game:GetService("RunService")
local interval = math.random(0.25, 1.5)
local coin = game.ServerStorage.coin
local counter = 0
local x = math.random(-254, 254)
local z = math.random(-255, 255)
runservice.Heartbeat:Connect(function(step)
counter = counter + step
if counter >= interval then
counter = counter - interval
local copy = coin:Clone()
copy.Parent = workspace
copy.Position = Vector3.new(x, 2, z)
x = math.random(-254, 254)
z = math.random(-255, 255)
interval = math.random(0.25, 1.5)
end
end)

桌面中处理触摸的脚本:

for _, v in pairs(workspace:GetChildren()) do
if v.Name == "coin" then
print("foo")
end
end

我希望这足以帮助你!

既然您是roblox脚本的新手,那么让我用可能对您有很大帮助的良好实践来回答您。首先,在这个场景中,您不需要使用心跳,而是可以简单地使用while循环或递归函数和简单的wait((。此外,您最好创建一个";硬币;工作区中的文件夹,以便不检查其他对象

local waitTime = math.random(25,150)/100 --random time between 0.25 and 1.5
while true do  --forever loop
wait(waitTime)   --waits desired time
local coin = game.ServerStorage.coin:Clone() --cloning your coin
coin.Parent = workspace.Coins --Coins folder
coin.Position = Vector3.new(math.random(0,10),2,math.random(0,10)) --you must use your own position
coin.Touched:Connect(function(hitPart) --here is the touched function
local plr = game.Players:FindFirstChild(hitPart.Parent.Name) --check if the hitPart is part of a player
if plr then 
plr.leaderstats.Coins.Value =  plr.leaderstats.Coins.Value + 1--here you can increment your coins value in your own value
coin:Destroy()--destroys the coin
end
end)
waitTime = math.random(25,150)/100 --set a new random value to wait next
end

你还提到了一些关于在工作空间中循环每个硬币的内容,这就是为什么我说最好创建一个单独的文件夹。因此,我在StarterPlayerScripts中制作了一个本地脚本,代码如下:

local RunService = game:GetService("RunService") --service
RunService.RenderStepped:Connect(function() --function on every game frame
for i,v in pairs(workspace.Coins:GetChildren()) do --loop on every coin
v.Orientation = Vector3.new(v.Orientation.X,v.Orientation.Y+5,v.Orientation.Z) --increasing Orientation just on Y in order to rotate them 
end
end)

我在localscript上这样做是因为这只是一种视觉效果,而且在服务器端快速发送这么多函数从来都不是一个好主意。这是我为你制作的游戏:https://www.roblox.com/games/5842250223/Help-for-TextBasedYoutube你可以编辑这个地方。

换句话说,回答";当任何具有相同名称的对象被触摸时,如何运行代码"创建对象时,您需要为其设置函数。

编辑:在短时间内向服务器发送多个请求也不是一个好主意,我建议你每隔2到3秒或更长时间创建一个硬币。

相关内容

最新更新