It was not possible to instantiate a scene, why?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By CarlitosCUeba

Actually, everything was fine until today, but for some reason the scene I was instantiating is returning null.

using Godot;
using System;

public class Bodyx  : KinematicBody2D
{
    //Atributos
    private int ContadorTiro = 0;
    //Movimentacao
    private PackedScene BulletNode;
    public override void _Ready()
    {
        BulletNode = GD.Load<PackedScene>("res://Body/Bullet.tscn");
    }
    protected void RetornoDirecao(int speed, Vector2 direcao, float delta)
    {
        MoveAndCollide(direcao.Normalized() * speed * delta);
        
    }
    
    protected GlobalVariable VariavelGlobal()
    {
        var globalVariable =  (GlobalVariable)GetNode("/root/GlobalVariable");
        return globalVariable;
    }
    protected void ToFire(bool Input, int TempoDeSaida)
    {
        
        
        
        Area2D Bullet = BulletNode.Instance() as Area2D;
        if(Input && ContadorTiro == 0)
        {
            var Rotation = (GetGlobalMousePosition()- GlobalPosition).Angle();
            
            Bullet.Rotation = Rotation;
            Bullet.Position = Position;
            GetParent().GetParent().AddChild(Bullet);
            
            ContadorTiro = TempoDeSaida;
        }
        else if(ContadorTiro > 0)
        {
            ContadorTiro -= 1;
        }
    } 


}

*I’m talking about BulletNode
*This code is a class that is used by Player and Enemy, however I am instantiating a
generic bulllet

Until recently the code was working but now this happens:

E 0:00:01.623 void Bodyx.ToFire(Boolean , Int32 ):
System.NullReferenceException: Object reference not set to an instance
of an object. <Erro C++> Unhandled exception <Origem C++>
C:\Users\dulou\OneDrive\Documentos\Jogo 001\Body\Bodyx.cs:30 @ void
Bodyx.ToFire(Boolean , Int32 )() Bodyx.cs:30
@ void Bodyx.ToFire(Boolean , Int32 )()
Player.cs:28 @ void Player.Fire()()
Player.cs:52 @ void Player._PhysicsProcess(Single )()

:bust_in_silhouette: Reply From: juppi

This is null: Area2D Bullet = BulletNode.Instance() as Area2D;

Who is calling the method protected void ToFire(bool Input, int TempoDeSaida) ?

The _Ready() function ONLY gets called, if the script is attached to a node of your scene hierarchy.
If not, you should replace the _Ready() method with a constructor.

Like this:

public Bodyx()
{
    BulletNode = GD.Load<PackedScene>("res://Body/Bullet.tscn");
}

The game player, he calls this method.
The Input parameter is, of course, what controls the triggers, in the player I use an .IsActionPressed(). And TempoDeSaida serves to control their speed

Wow! I didn’t even consider using builders, nor did I think about it.
I will test. I’ve already tried a lot of things, so I stopped the project temporarily
Thanks!xD

CarlitosCUeba | 2021-06-14 20:57