Godot Version
v4.2.1-stable_mono_win64
Question
Hello, I am trying to make a character pathfind to the mouse position, and I have managed to make it work, but it throws a couple hundred NullReference errors a second while doing it.
This is the script I am using for pathfinding:
using Godot;
using System;
public partial class KnWarriorBlue : CharacterBody2D
{
[Export] public NavigationAgent2D navigationAgent2D;
public Vector2 direction;
public int speed = 200;
public double accel = 5.0;
public Vector2 mousePos;
public override void _Ready() {
GD.Print(navigationAgent2D.GetCurrentNavigationPath(), "navigationAgent2D.GetCurrentNavigationPath()"); // this errors out
GD.Print(GetTransform(), "GetTransform()");
GD.Print(GetGlobalMousePosition(), "GetGlobalMousePosition()");
GD.Print(navigationAgent2D.TargetPosition, "(navigationAgent2D.TargetPosition");
GD.Print(navigationAgent2D.GetNextPathPosition(), "navigationAgent2D.GetNextPathPosition()");
GD.Print(GlobalPosition, "GlobalPosition");
}
public override void _Process(double delta) {
navigationAgent2D.TargetPosition = GetGlobalMousePosition(); // this errors out
direction = navigationAgent2D.GetNextPathPosition()- GlobalPosition;
direction = direction.Normalized();
Velocity = Velocity.Lerp(direction * speed, (float)(accel * delta));
MoveAndSlide();
}
}
The export field is assigned a NavigationAgent2D that is a child node of the CharacterBody2D.
Stuff in ready I just use for debugging, to see if I get errors trying to call the methods. The errors in debug open the script on lines 14 and 23 (the first lines of ready and process).
The line in the process that throws an error seems to get executed exactly half the time, when I used GD.Print in the process before the line to check the values of TargetPosition and GetGlobalMousePosition it only printed TargetPosition skipping a frame.
I don’t know what goes wrong, would greatly appreciate any help.