Search code examples
c#godot4

How Do I Spawn a new object in Godot 4.x


I'm currently making a game, and I want my character to shoot projectiles at the enemy. I'm facing an issue where when I click, the bullet doesn't fire. Here's my code so far:

public partial class PotatoCannon : Sprite2D
{
    public Timer cooldown;

    [Export]
    public PackedScene boolet { get; set; }

    public override void _Ready()
    {
        cooldown = GetNode<Timer>("CannonCooldown");
        cooldown.Autostart = false;
    }
    public override void _PhysicsProcess(double delta)
    {
        GD.Print(cooldown.TimeLeft);
        LookAt(GetGlobalMousePosition());
        RotationDegrees = Math.Abs(RotationDegrees);
        if (RotationDegrees%360>=90.0 && RotationDegrees%360<=270.0)
        {
            FlipV = true;
        }
        else
        {
            FlipV = false;
        }
        if (Input.IsActionJustPressed("shoot") && cooldown.TimeLeft == 0)
        {
            bullet Bullet = boolet.Instantiate<bullet>();
            this.AddChild(Bullet);
            cooldown.WaitTime = 1;
            cooldown.Start();
        }
    }
}

oh and btw, the error message is

E 0:00:49:0157   PotatoCannon.cs:24 @ void PotatoCannon._PhysicsProcess(Double ): System.NullReferenceException: Object reference not set to an instance of an object.

Solution

  • Exported variables are supposed to be available and settable from the editor Inspector.

    However, since that is not working, let us instead load PackedScene you need:

        public PackedScene boolet { get; set; }
        public override void _Ready(){
            // ...
            boolet = GD.Load<PackedScene>(PATH);
        }
    

    Here you need to replace PATH with the "res://..." path of the bullet scene you want to instantiate.

    By loading it in _Ready and storing it in the field boolet, it should be available when you need to instantiate in _PhysicsProcess.