如何解决Roblox 尝试使用“WaitForChild”索引 nil
我正在编写一个脚本来查找目标玩家,如果玩家内部的值为真,则 MoveTo()
。它输出一个错误,说
Attempt to index nil with 'WaitForChild'
这是一个服务器脚本,错误位于 plr:WaitForChild("Crime",1)
。
这是:
local crime= false
local plr = nil
function findNearestTorso(pos)
local list = game.Workspace:children()
local torso = nil
local dist = 10000
local temp = nil
local human = nil
local temp2 = nil
for x = 1,#list do
temp2 = list[x]
if (temp2.className == "Model") and (temp2 ~= script.Parent) then
temp = temp2:findFirstChild("HumanoidRootPart")
human = temp2:findFirstChild("Humanoid")
if (temp ~= nil) and (human ~= nil) and (human.Health > 0) then
if (temp.Position - pos).magnitude < dist then
plr = game.Players:WaitForChild(temp2.Name,1)
print("plr")
torso = temp
dist = (temp.Position - pos).magnitude
end
end
end
end
return torso
end
while true do
wait(1)
local target = findNearestTorso(script.Parent.HumanoidRootPart.Position)
if target ~= nil and plr:WaitForChild("Crime",1).Value==true then
script.Parent.Humanoid:MoveTo(target.Position,target)
end
end
解决方法
您不能保证在 const callPressableFunc = () => {
console.log('I want to print this');
};
return (
<View>
<Pressable
style={{width: 100,height: 100,backgroundColor: 'yellow'}}
onPress={callPressableFunc}
ref={pressableRef}
/>
<Button title="Klick me" onPress={callPressableFunc} />
</View>
);
运行后设置 plr
。
您在 3 个嵌套 if 语句的主体中设置了 findNearestTorso
。
plr
如果您的任何 if 语句不正确,if (temp2.className == "Model") and (temp2 ~= script.Parent) then
--...
if (temp ~= nil) and (human ~= nil) and (human.Health > 0) then
if (temp.Position - pos).magnitude < dist then
plr = game.Players:WaitForChild(temp2.Name,1)
--...
将是 plr
为了解决这个问题,我们可以简单地更改发生错误的条件,在尝试调用 nil
之前检查 plr
是否为 nil
plr:WaitForChild
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。