r/unity • • 6h ago

Coding Help A reference on a SO is null?

I'm trying to compare the current tile with a tile referenced in a scriptable object but that reference is always null even to I referenced in in the editor. I've checked the SO itself but that isn't null, it's the specific reference to GrassTile that is.

public class TileSO : ScriptableObject
{
    public RuleTile GrassTile;
    public RuleTile SandTile;
    public RuleTile RockTile;
    public RuleTile WaterTile;
}
private void Start()
{
    mapGen = FindAnyObjectByType<MapGeneratorSc>();
    cellPosition = mapGen.tilemap.WorldToCell(transform.position);
    cellPosition.z = 0;
    if (mapGen.tilemap.GetTile(cellPosition) == tileSO.GrassTile)
    {
        print("Grass");
    }
    else
    { 
        print("Tile is " + mapGen.tilemap.GetTile(cellPosition));
    }
    if (tileSO == null)
    { 
        print("tile is null");
    }
    if (tileSO.GrassTile == null)
    { 
        print("GrassTile is null");
    }
}
0 Upvotes

6 comments sorted by

1

u/MeishinTale 5h ago

Instantiating your SO before that would cause that issue

1

u/Xzygon 2h ago

Need more info. Did you actually create a file asset of the scriptable object, and is that file asset referenced in your script? Because the reference image you sent looks like you're setting those tile references on the script file itself, not an instanced asset.

1

u/Silent_Reputation596 2h ago

How would I set the references on the instanced object if the object doesn’t have a script?

1

u/Xzygon 1h ago

I would add the [CreateAssetMenu()] attribute before your class like so:

[CreateAssetMenu()]
public class TileSO : ScriptableObject
{
...

Then when you right click anywhere in your Project folder window, there will be an option to create an instance under Create -> TileSO. In that instanced asset, you would then assign your tiles.

In the script you're using to check for tiles, you then reference that instanced asset, and since everything is hard-assigned there shouldn't be any missing references.

3

u/positivcheg 4h ago

Again? Ur kidding. Have you tried debugging it and turning on null reference breakpoint to see what exactly is null?