1

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.
  • What exactly is happening? a. nothing. b. it causes an error (which?) c. it instantiates the bullet but it does not move. d. something else? – Theraot Jul 30 '23 at 00:16
  • when I left click, which is associated with "shoot", it does nothing and gives and error of `E 0:00:49:0157 PotatoCannon.cs:24 @ void PotatoCannon._PhysicsProcess(Double ): System.NullReferenceException: Object reference not set to an instance of an object.` – Nanmuhong Ye Jul 30 '23 at 01:10
  • I'm guessing the line 24 that the error mentions is this `bullet Bullet = boolet.Instantiate();` correct? That would mean that the `PackedScene boolet` is not set. Double check you set it. You could try `GD.Print(boolet);` to see if it has a value. – Theraot Jul 30 '23 at 01:20
  • it returns null. Is there any other way to spawn a new object using code other than this? – Nanmuhong Ye Jul 30 '23 at 01:36
  • Arguably. You could build an scene `Node` by `Node` in code. However, the issue is not instantiating your scene, the issue is getting a reference to it. – Theraot Jul 30 '23 at 01:45

1 Answers1

1

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.

Theraot
  • 31,890
  • 5
  • 57
  • 86