为什么 For 循环 Return "attempt to get length of a Vector3 value"

Why Does A For Loop Return "attempt to get length of a Vector3 value"

我不知道这段代码有什么问题,它的字面意思是一个非常好的 for 循环正在尝试获取 vector3 值。

local locations = {}
local Players = game:GetService("Players")

local function SplitString(String)

    local CurrentString = ""
    local x = 1

    for i = 1, #String do

        local FullString = string.sub(String,1,i)
        local Character = string.sub(String,i,i)
        local CurrentString = string.sub(String, x, i)
        print(locations[1])

        if Character == "," then
            CurrentString = string.sub(String,x,i-1)
            table.insert(locations,CurrentString)
            x = i + 1
            CurrentString = string.sub(String, x , i)
            print(locations)
        end

        --Add the character to the string.
        if Character == " " then
            x = i + 1
            CurrentString = string.sub(String, x, i + 1)
        end
        if #FullString + 1 == #String then
            table.insert(locations, CurrentString)
        end
    end
end



Players.PlayerAdded:Connect(function(player)
    player.CharacterAdded:Connect(function(char)
        local humanoidrootpart = char:WaitForChild("HumanoidRootPart")
        
        wait(5)
        
        while humanoidrootpart do
            local location = humanoidrootpart.position
            print(location)
            
            SplitString(location)
            print(locations[1])
            
            local RoundLocatX = math.floor(locations[1]*50)/50
            local RoundLocatZ = math.floor(locations[3]*50)/50
            local RoundLocatXLength = RoundLocatX.length
            local RoundLocatZLength = RoundLocatZ.length
            
            
            if RoundLocatX > 50 then
                print('hi')
            end
            wait(1)
        end
    end)
end)

这是错误:

ServerScriptService.Terrain Generation:9: attempt to get length of a Vector3 value

我会 post 在 roblox 论坛上写这个,但他们很愚蠢,需要一些愚蠢的阅读时间才能 post 在上面。

你的错误指向这一行:

for i = 1, #String do

并说您正在尝试获取 Vector3 对象的长度。这意味着 #String 没有按预期工作。因此,查看您传递给 SplitString 函数的对象...

        local location = humanoidrootpart.position
        print(location)
        SplitString(location)

您的 location 变量是 Vector3,不是字符串,它不支持长度运算符,#

但您不必将其解析为字符串即可从中获取值。因为它是一个Vector3,你可以简单地索引其中的不同值。

        local location = humanoidrootpart.Position
        
        local RoundLocatX = math.floor(location.X * 50) / 50
        local RoundLocatZ = math.floor(location.Z * 50) / 50