Error:Out of bounds get index '0' (on base: 'Array [vector2]')

Godot Version

4.3 (stable)

Question

Hi,when I tried to make patrol system for my enemy my game suddenly crash and I got error : Out of bounds get index ‘0’ (on base: ‘Array [vector2]’) and this is my enemy full script:

extends CharacterBody2D

@export var patrol_points : Node

const GRAVITY = 1000
const SPEED = 2800

enum state {idle, walk}
var current_state : state
var direction : Vector2 = Vector2.LEFT
var number_of_points : int 
var point_positions : Array[Vector2]
var current_point : Vector2
var current_point_position : int

func ready():
	if patrol_points != null:
		number_of_points = patrol_points.get_children().size()
		for point in patrol_points.get_children():
			point_positions.append(point.global_position)
		current_point = point_positions[current_point_position]
	else:
		print("No patrol points")
	
	current_state = state.idle
	
	

func _physics_process(delta: float):
	enemy_gravity(delta)
	enemy_idle(delta)
	enemy_walk(delta)
	
	move_and_slide()


func enemy_gravity(delta : float):
	velocity.y += GRAVITY * delta


func enemy_idle(delta : float):
		velocity.x = move_toward(velocity.x, 0, SPEED * delta)
		current_state = state.idle

func enemy_walk(delta : float):
	
	if abs(position.x -current_point.x) > 0.5:
		velocity.x = direction.x * SPEED * delta
		current_state = state.walk
	else:
		current_point_position += 1
	
	if current_point_position >= number_of_points:
		current_point_position = 0
		
	current_point = point_positions[current_point_position]
	
	if current_point.x > position.x:
		direction = Vector2.LEFT
	else:
		direction = Vector2.RIGHT

On point_positions? The line number from the backtrace would be nice.

point_positions might be empty hence before you try to pick from it use is_empty():

if !point_positions.is_empty():
  current_point = point_positions[current_point_position]

The game doesn’t crash but now the problem is the enemy goes to right infinitely and never comeback to the right

You must have some new bug in enemy_walk(delta) then. You never set velocity.x to 0. Try doing that when you reached a point and head for the next one.

Sorry I’m a beginner how to do that?

No problem. I have more hints for you.

The enemy doesn’t do his patrol at all, just wanders off? Then the list of point_positions is indeed empty, at least when the node is added to the scene, but the code for setting the enemy’s velocity is still being executed.
I do wonder though, if the list of points is empty, then current_point should be null or do you set it somewhere else? Because if you have set it to Vector2(0,0) then the enemy would walk towards it even if there’s no points_positions.

Oww I’m sorry the enemy goes to right and never go to left i just realized I typed wrong