themusicslm00se
themusicslm00se

Reputation: 3

I get a NullReferenceException error when trying to use Tilemap.GetTile in unity

I have my code set up so that when the spacebar is clicked, the console prints out the current tile the player is on. However, I get this long error instead. Can someone please tell me how to fix this and/or why this is happening? This is the error:

NullReferenceException UnityEngine.Tilemaps.Tilemap.GetTileAsset (UnityEngine.Vector3Int position) <0x3886fc90 + 0x0005a> in :0 UnityEngine.Tilemaps.Tilemap.GetTile (UnityEngine.Vector3Int position) (at C:/buildslave/unity/build/Modules/Tilemap/ScriptBindings/Tilemap.bindings.cs:113) Player.Dig () (at Assets/Scripts/Player.cs:56) Player.Update () (at Assets/Scripts/Player.cs:28)

My code is:

private void Dig()
{
    if (Input.GetKeyDown(KeyCode.Space))
    {
        Vector3Int playerPos = grid.WorldToCell(player.transform.position);
        Tilemap tilemap = new Tilemap();
        Debug.Log(tilemap.GetTile(playerPos));
    }
}

The code is in a method that runs in update.

Upvotes: 0

Views: 1010

Answers (1)

derHugo
derHugo

Reputation: 90769

Tilemap is a Component and as every other Component should never be created using new! This is forbidden in Unity. A Component can only exist attached to a GameObject e.g. using AddComponent or by Instantiate a prefab with the components attached.

Best way however would be to Create a Tilemap already in the Editor and either use it directly or store it as prefab.

Then you can reference it in a field like e.g.

public Tilemap tilemap;

Upvotes: 3

Related Questions