– Получаем ссылку на игрового персонажа (Humanoid) local character =…
- User
– Получаем ссылку на игрового персонажа (Humanoid) local character = game.Players.LocalPlayer.Character local humanoid = character:WaitForChild(“Humanoid”)
– Получаем ссылку на PathfindingService local pathfindingService = game:GetService(“PathfindingService”)
– Переменная для хранения текущего пути local currentPath = nil
– Создаем функцию, которая будет вызываться при клике правой кнопкой мыши local function onRightClick(mouse) – Получаем позицию, куда было кликнуто local targetPosition = mouse.Hit.Position
– Если уже существует активный путь, удаляем его if currentPath then currentPath:Cancel() currentPath = nil end – Создаем новый путь с помощью PathfindingService currentPath = pathfindingService:CreatePath() currentPath:ComputeAsync(character.HumanoidRootPart.Position, targetPosition) – Запускаем цикл, который будет обновлять позицию персонажа каждую секунду coroutine.wrap(function() while currentPath and currentPath.Status ~= Enum.PathStatus.Success do – Получаем следующую точку пути local waypoints = currentPath:GetWaypoints() local nextWaypoint = waypoints[1] – Перемещаем персонажа к следующей точке пути local direction = (nextWaypoint.Position - character.HumanoidRootPart.Position).unit humanoid:MoveToDirection(direction) wait(1) – Подождать 1 секунду (можно изменить интервал обновления) end end)()end
– Обработчик события клика правой кнопкой мыши game:GetService(“UserInputService”).InputBegan:Connect(function(input) if input.UserInputType == Enum.UserInputType.MouseButton2 then onRightClick(input.Position) elseif input.KeyCode == Enum.KeyCode.S then – Остановить движение персонажа humanoid:MoveTo(character.HumanoidRootPart.Position) end end) Роблокс выдет ошибку на этих строчках кода: "while currentPath and currentPath.Status ~= Enum.PathStatus.Success do --Получаем следующую точку пути local waypoints = currentPath:GetWaypoints() local nextWaypoint = waypoints[1]
-- Перемещаем персонажа к следующей точке пути local direction = (nextWaypoint.Position - character.HumanoidRootPart.Position).unit humanoid:MoveTo(character.HumanoidRootPart.Position + direction) wait(1) -- Подождать 1 секунду (можно изменить интервал обновления) end", сама ошибка "Players.RealTerrariumMan.PlayerGui.ClickMove:32: attempt to index nil with 'Position'" - Assistant
Ошибка "attempt to index nil with 'Position'" говорит о том, что переменная
nextWaypointравнаnil, и это приводит к ошибке при попытке обращения к полюPosition.Возможная причина этой ошибки заключается в том, что путь, возвращаемый
currentPath:GetWaypoints(), пуст или еще не был вычислен до достижения цели.Чтобы исправить это, вы можете добавить проверку перед вызовом метода
GetWaypoints():while currentPath and currentPath.Status ~= Enum.PathStatus.Success do -- Проверяем, есть ли путь и вычислены ли уже точки пути if currentPath.Status == Enum.PathStatus.Invalid or currentPath.Status == Enum.PathStatus.Cancelled then break end -- Получаем следующую точку пути local waypoints = currentPath:GetWaypoints() if #waypoints == 0 then break end local nextWaypoint = waypoints[1] -- Перемещаем персонажа к следующей точке пути local direction = (nextWaypoint.Position - character.HumanoidRootPart.Position).unit humanoid:MoveTo(character.HumanoidRootPart.Position + direction) wait(1) -- Подождать 1 секунду (можно изменить интервал обновления) end