触摸任何同名对象时如何 运行 编码

How to run code when any object with the same name is touched

所以我正在尝试在 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 脚本编写的新手,那么让我用可能对您有很大帮助的良好做法来回答您的问题。 首先,在这种情况下,您不需要使用 Heartbeat,而是可以简单地使用一个 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 秒或更长时间创建一个硬币。