Skip to content

Godot Common Mistakes

Valk edited this page Aug 9, 2023 · 3 revisions

Resource is not showing up in inspector

// The [GlobalClass] attribute must be added in order for Godot to see this resource properly in the inspector
// The sealed modifier is added to prevent inheriting from this class as it will never be needed. Also performance may be increased by adding this modifier.
[GlobalClass]
public sealed partial class Test : Resource
{
    // Note that this must be a public field as Godot does not support properties in resources
    [Export] public int Integer;

    // Note that Godot does not support System.Collections.Generic.(...)
    // Godot does support Godot.Collections.(...) but these are generally not nice to work with when assigning values in the inspector
}

Tiles are not showing up in tilemaps

You try to use tileMap.SetCell(...) to set a cell in the tilemap but it instead wipes the cell.

This could be do to many reasons

  • The sourceId is set to -1 or not set to the value that was assigned to it in the editor. Note that the sourceId is assigned by the editor, you have no control over this number, you will have to check this number by hovering your mouse over any of the tiles in the tilemap.
  • The atlasCoords was set to (-1, -1) or to a tile atlas position that does not exist.

Copying Arrays

Lets say you have hotkeys stored as Dictionary<StringName, Array<InputEvent>>. You want to store a copy of this to keep track of the default hotkeys. So you do the following.

Hotkeys = new(DefaultHotkeys);

Even though they are now stored in different dictionaries, they are still referencing the same array and each element in that array is referencing the same element. This means if you change a hotkey, the default hotkeys dictionary will also be updated.

In order to fix this we have to ensure everything is unique.

// Create a new dictionary
Hotkeys = new();

foreach (var element in DefaultHotkeys)
{
    // Create a new array
    var arr = new Array<InputEvent>();

    foreach (var item in DefaultHotkeys[element.Key])
        // Ensure each InputEvent is unique
        // Note that Duplicate() is a built in Godot function from the Godot.Resource class
        arr.Add((InputEvent)item.Duplicate());

    Hotkeys.Add(element.Key, arr);
}