【问题标题】:Why is the for loop not creating a instance in roblox studio?为什么 for 循环没有在 roblox studio 中创建实例?
【发布时间】:2021-08-09 04:43:56
【问题描述】:

我制作了一个脚本,在每个部分都创建了一个网格,但它不起作用? 它随机偏移网格 我尝试过使用打印调试(如print("Created Mesh")print("Offsetting..")),但它打印出来没有问题(代码仍然不起作用。) 我尝试更改代码,但它输出相同的结果。 这是代码。

for i, v in pairs(workspace:GetDescendants()) do
if v.ClassName == string.match(v.ClassName, "Part") then
    local mesh = Instance.new("SpecialMesh",v)
    mesh.MeshType = Enum.MeshType.Brick
    while true do
        for i = 0,math.random(0,5) do
            mesh.Offset = Vector3.new(math.random(-100,100)*.01,math.random(-100,100)*.01,math.random(-100,100)*.01)
            wait(0.1)
        end
        wait(math.random(10,30)*.1)
    end
end
end

【问题讨论】:

    标签: roblox


    【解决方案1】:

    内部的while循环没有退出情况,所以它创建的第一个对象将永远阻塞原来的for循环。

    如果您想为网格设置动画,我建议您将 while 循环逻辑移动到网格内部的脚本中。这使得每个脚本都能够并行工作,而不会阻塞创建网格的原始 for 循环。

    因此,创建一个脚本并将其放在类似ReplicatedStorage 的位置,并将其命名为类似AnimationScript

    -- in ReplicatedStorage.AnimationScript...
    local function getValue()
        return math.random(-100, 100) * 0.01
    end
    
    local mesh = script.Parent
    while script.Parent ~= nil do
        for i = 0, math.random(0, 5) do
            mesh.Offset = Vector3.new(getValue(), getValue(), getValue())
            wait(0.1)
        end
        wait(math.random(10, 30) * 0.1)
    end
    

    然后,将该脚本克隆到您创建的每个网格中。这样,循环不会被阻塞,动画会在不同的脚本线程中处理。

    -- create a brick template
    local mesh = Instance.new("SpecialMesh")
    mesh.MeshType = Enum.MeshType.Brick
    local animationScript = game.ReplicatedStorage.AnimationScript:Clone()
    animationScript.Parent = mesh
    
    -- put meshes inside all parts
    for _, part in pairs(workspace:GetDescendants()) do
        if part:IsA("BasePart") then
            local brickMesh = mesh:Clone()
            brickMesh.Parent = part
        end
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-20
      • 2018-04-02
      • 1970-01-01
      • 2020-11-26
      • 1970-01-01
      • 2013-04-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多