Hey everyone, usually I debug my code using chatgpt since I’m still new and don’t want to be posting here every 20 minutes. Ran into an issue with this one that not even AI can crack… Worst part is I imagine this would be pretty simple.
Code
extends Node2D
Preload packed scenes for upgrades
@onready var frequency: PackedScene = null
@onready var arrowstrength: PackedScene = null
Reference the position nodes for upgrade spawning
@onready var pointone = $one
@onready var pointtwo = $two
Selection array holding the upgrade scenes
var selection = [frequency, arrowstrength]
Called when the node enters the scene tree for the first time.
func _ready():
# Load the packed scenes for upgrades from the specified paths
frequency: PackedScene = preload(“res://arrowstrength.tscn”)
arrowstrength: PackedScene = preload(“res://frequencyupgrade.tscn”)
Called every frame. ‘delta’ is the elapsed time since the previous frame.
func _process(delta):
# Check if the game is in a specific mode and if upgrades need to be spawned
if System.mode == 2 and System.needtospawn:
spawn_upgrades() # Call the function to spawn upgrades
System.needtospawn = false # Reset the flag to prevent multiple spawns
Function to spawn upgrades at designated points
func spawn_upgrades():
# Check if the position nodes are valid to prevent errors
if not is_instance_valid(pointone) or not is_instance_valid(pointtwo):
return # Exit the function if the points are not valid
# Randomly select and instantiate an upgrade from the selection array
var instance_one = selection[randi() % selection.size()].instantiate()
var instance_two = selection[randi() % selection.size()].instantiate()
# Set the positions of the instances to the designated points
instance_one.global_position = pointone.global_position
instance_two.global_position = pointtwo.global_position
# Add the instantiated upgrades to the parent node of this script
get_parent().add_child(instance_one)
get_parent().add_child(instance_two)
So basically every time I try to do it it either fully crashes the game (as in it freezes), it does nothing, or most commonly I get an error that it can’t instantiate on a nil instance. From what I’ve learned so far this should work?
Any advice I’ve seeked online so far seems to indicate that this is correct. I will also add that when I removed the random aspect it worked perfectly so I know the preloading is working okay.
Any advice on this would be perfect