Roblox Studio Lua:模型无法跟随玩家,同脚本在普通部件可运行
问题根源与解决方案
你的脚本针对单个部件能正常工作,但挂载到**模型(Model)**上失效,核心原因是:BodyPosition 和 BodyGyro 必须作用于单个 BasePart 实例,不能直接绑定到 Model 本身。模型是多个部件的容器,需要指定一个主部件(PrimaryPart)来承载这些约束。
修复步骤
1. 先配置目标模型
- 打开模型的属性面板,设置
PrimaryPart:选择模型中作为核心的部件(比如模型的主体部件) - 确保模型所有部件都未锚定(Anchored = false),且没有其他冲突的约束/脚本
2. 修改脚本核心逻辑
调整脚本,让约束挂载到模型的 PrimaryPart 上,而非模型本身:
local petModel = script.Parent -- 提前检查模型是否设置了PrimaryPart,避免后续报错 assert(petModel:IsA("Model") and petModel.PrimaryPart, "目标模型必须设置PrimaryPart") function givePet(player) local character = player.Character if not character then return end local humRootPart = character:FindFirstChild("HumanoidRootPart") if not humRootPart then return end -- 克隆模型并设置父级 local newPet = petModel:Clone() newPet.Parent = character -- 获取克隆后模型的PrimaryPart local petRoot = newPet.PrimaryPart if not petRoot then return end -- 创建BodyPosition并挂载到PrimaryPart local bodyPos = Instance.new("BodyPosition") bodyPos.MaxForce = Vector3.new(math.huge, math.huge, math.huge) bodyPos.Position = humRootPart.Position + Vector3.new(2, 2, 3) bodyPos.Parent = petRoot -- 创建BodyGyro并挂载到PrimaryPart local bodyGyro = Instance.new("BodyGyro") bodyGyro.MaxTorque = Vector3.new(math.huge, math.huge, math.huge) bodyGyro.CFrame = humRootPart.CFrame bodyGyro.Parent = petRoot -- 循环更新位置与朝向 while task.wait() do -- 先检查角色和部件是否还存在,防止报错 if not character:IsDescendantOf(game) or not petRoot:IsDescendantOf(game) then break end bodyPos.Position = humRootPart.Position + Vector3.new(2, 2, 3) bodyGyro.CFrame = humRootPart.CFrame end end game.Players.PlayerAdded:Connect(function(player) -- 处理角色已加载的情况(比如玩家加入时角色已经存在) if player.Character then task.spawn(givePet, player) end player.CharacterAdded:Connect(function() givePet(player) end) end)
额外排查项
- 检查模型是否有冲突的约束(比如已存在的BodyPosition/BodyGyro),移除后再测试
- 确保脚本的运行环境正确:该脚本应该放在 ServerScriptService 或模型内(作为服务器脚本),如果是本地脚本要调整网络所有权逻辑
- 测试时可以在输出面板查看是否有报错,比如找不到PrimaryPart、HumanoidRootPart不存在等问题
内容的提问来源于stack exchange,提问作者Dr_ArmyDevRBX
相关产品推荐
相关产品推荐

