Player is null no matter what I do and bullet won't spawn

Godot Version 4.4.1

I am brand new. I’ve only made a couple of tutorial games in the past and learned scripting from a few lessons on GDscript. My goal with this script is to have a bullet shoot at the player by an enemy (spawned randomly from a pool of 5 different markers).

But no matter what I do, my player node is returning null. And because of that, when the bullet is meant to shoot at the player, my game crashes. I have looked in the remote tab to make sure the node path is correct, I have tried both “get_node()” and CharacterBody2d = Player as well as making node a unique path by adding %.

Here is the full script for the enemy (1), the player (2), the bullet (3) and the enemy spawn (4) please help me
enemy


player

bullet

enemy spawn, for some reason is “relative to” player

Appreciate the well thought out question and providing us all of that information. Two things:

  1. The problem is with your scene tree. We need to see a screenshot of that to see what your problem is.
  2. When you post code, please copy and paste it instead of using screenshots. It’s hard to read and it creates a lot of work if we want to give you alternate code because we have to type it out ourselves. When you paste it put ``` on it’s own line above and below the code and it will be formatted correctly.
2 Likes

Ok. Here is the scene tree. Also would you like me to copy and paste the code instead or is this enough?


I’m not sure unique names are meant to be used across different scenes like that. Also, when you use get_node() you are only looking for local nodes in the same scene. You might want to try get_tree().current_scene.get_node() instead… But that’s not a good approach.

If you want a global reference for your player you might want to use groups or an autoload that saves the player reference.

For the groups approach, make a group named player and put only the player inside that, then you get the reference by calling get_tree().get_first_node_in_group(“player”).

For the autoload approach, let’s say you create a script named game.gd:

extends Node
var player

Then you set it as an autoload in the ProjectSettings and on the player _init() or _ready() function you call:

func _init():
	Game.player = self

And when you need a player ref you can get it by calling Game.player from anywhere:

func do_something():
	print(Game.player)
2 Likes

This fixed it! Yay! Thank you. I will research how globals and autoloads work after this. Thank you

1 Like

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