-1

I've been programming in Godot C# for fun lately, and I'm currently writing code for a room generator. For some reason, I'm getting a NullReferenceException at line 25 of the following code:

using Godot;
using System;
using System.Collections.Generic;

public class World : Node2D
{
    private const int ROOM_NUM = 5;
    private const int ROOM_WIDTH = 512;
    private const int ROOM_HEIGHT = 288;

    private Random rnd = new Random();
    private Vector2 pos = new Vector2(0, 0);
    private List<Vector2> posList;
    private int posPos = 0;

    // Called when the node enters the scene tree for the first time.
    public override void _Ready()
    {
        PackedScene[] roomScenes = { ResourceLoader.Load<PackedScene>("res://Scenes/WorldSections/GurdurRoom.tscn"), ResourceLoader.Load<PackedScene>("res://Scenes/WorldSections/ArenaRoom.tscn"), ResourceLoader.Load<PackedScene>("res://Scenes/WorldSections/EndRoom.tscn") };
        
        for (int i = 0; i < ROOM_NUM; i++)
        {
            TileMap newRoom = roomScenes[rnd.Next() % 2].Instance<TileMap>();
            newRoom.Position = pos;
            posList.Add(pos);
            AddChild(newRoom);
            
            while (!posList.Contains(pos))
            {
                switch (rnd.Next() % 4)
                {
                    case 0:
                        pos.y -= ROOM_HEIGHT;
                        break;
                    case 1:
                        pos.y += ROOM_HEIGHT;
                        break;
                    case 2:
                        pos.x -= ROOM_WIDTH;
                        break;
                    case 3:
                        pos.x += ROOM_WIDTH;
                        break;
                }
            }
        }
        
        TileMap endRoom = roomScenes[2].Instance<TileMap>();
        endRoom.Position = pos;
        AddChild(endRoom);
    }
}

My best idea as of right now is that for some reason the room is not giving an instance?

Please Help, I'm dumb stupid and bad.

FyreWolf
  • 11
  • 1
  • 2
  • 2
    `posList` will be `null` until you assign a `List<>` instance to it (e.g. `private List posList = new List();`), which you never do. For future reference, it's helpful to the reader to use something other than line numbers to indicate any problematic code so they don't have to count them out themselves. – Lance U. Matthews May 21 '22 at 22:32

0 Answers0