r/unity • • 4h ago

Coding Help Null Reference in SO

I have a SO with a reference to a rule tile. I am then trying to reference that rule tile with a mono behaviour ingame but I keep getting "Object reference not set to and Instance of an object" for GrassTile.

SO:

public RuleTile GrassTile;
public RuleTile SandTile;
public RuleTile RockTile;
public RuleTile WaterTile;

MB:

public class TileDataSc : MonoBehaviour
{

    [SerializeField] TileSO TileSO;
    MapGeneratorSc mapGen;

    Vector3Int cellPosition;

    private void Start()
    {
        mapGen = FindAnyObjectByType<MapGeneratorSc>();
        cellPosition = mapGen.tilemap.WorldToCell(transform.position);
        if (mapGen.tilemap.GetTile(cellPosition) == TileSO.GrassTile)
        { 
            print("Grass");
        }
    }
}
3 Upvotes

5 comments sorted by

1

u/Demi180 4h ago

Do you have the SO assigned to TileSO?

1

u/Silent_Reputation596 4h ago

Yes

2

u/Demi180 3h ago

You're sure the error mentions GrassTile? Maybe mapGen is null, or .tilemap.

Or maybe you have a duplicate of TileDataSc somewhere. Add some null checks and see what's actually null here. You can pass in the the gameObject to a Debug.Log call and it'll highlight it in the Hierarchy when you select that message in the console, like this: Debug.Log($"Something is null on {name}", gameObject);

1

u/lemming1607 28m ago

If grasstile is null, it wouldn't throw the error you see...the boolean would evaluate to true or false for tileso.grasstile

What throws the error is tileSO is null, because your code is trying to read a field of tileSO when TileSO doesnt exist in the code block

You need to double check that the monobehvaior is in the scene and it has the serialized field set

1

u/JaggedMetalOs 17m ago

Pot a break point on that line and use the debugger to see what is and isn't set.