Invalid set index 'mesh' (on base: 'Nil') with value of type 'ArrayMesh'

Godot Version

v4.2.2.stable.official [15073afe3]

Question

Hi! I’m just getting started with godot and being a game developer, so I follow this tutorial and not getting idea what’s wrong with it. Here the error:

Invalid set index 'mesh' (on base: 'Nil') with value of type 'ArrayMesh'.

and the code:

@tool

extends Node3D

@export var WEAPON_TYPE : Weapons:
	set(value):
		WEAPON_TYPE = value
		#print(value)
		load_weapon()

@onready var weapon_mesh : MeshInstance3D = %WeaponMesh
@onready var weapon_shadow : MeshInstance3D = %WeaponShadow

# Called when the node enters the scene tree for the first time.
func _ready():
	#print(WEAPON_TYPE.mesh)
	load_weapon()

func load_weapon():
	weapon_mesh.mesh = WEAPON_TYPE.mesh
	position = WEAPON_TYPE.position
	rotation_degrees = WEAPON_TYPE.rotation
	weapon_shadow.visible = WEAPON_TYPE.shadow

I notice something in the error details that the weapon_mesh and weapon_shadow is still set as null

This is inside the weapon:
image

and this is how I install the mesh:

Did I do something wrong in it? I really don’t know what is happening that causing that. Could anyone help me?

Thanks!

1 Like

Because the set function occurs before the @onready var weapon_mesh : MeshInstance3D = %WeaponMesh statement, it attempts to access the variable before it is fully initialized and ready. This can lead to issues since the node hierarchy might not be fully constructed at the time of execution.

To ensure that all nodes are properly initialized and ready before accessing them, you can delay the execution of certain functions until the node is ready.

1 Like
func load_weapon():
	if not $".".is_node_ready():
		await $".".ready
	
	print("Weapon mesh and weapon shadow is ready!")
	weapon_mesh.mesh = WEAPON_TYPE.mesh
	position = WEAPON_TYPE.position
	rotation_degrees = WEAPON_TYPE.rotation
	weapon_shadow.visible = WEAPON_TYPE.shadow

I tried to use that and yes. It’s working. I really appreciate it.
Thank you so much! :raised_hands:

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.