Why isn't this instantiation cast working?

So i am trying to directly cast a instantiated object as my custom component ClickableTile.

TileType tt = tileTypes[tiles[x, y]];
var tile = Instantiate(tt.tileVisualPrefab, new Vector3(x, y, 0), Quaternion.identity) as ClickableTile;

This returns null.

ClickableTile.cs looks like this and are attached to the prefab:

public class ClickableTile : MonoBehaviour
    public int tileX;
    public int tileY;
    public TileMap map;

    void OnMouseUp()

        map.MoveSelectedUnitTo(tileX, tileY);

Why isnt this working? I thought that we could cast to any component on object?

This works:

TileType tt = tileTypes[tiles[x, y]];
GameObject tile = (GameObject)Instantiate(tt.tileVisualPrefab, new Vector3(x, y, 0), Quaternion.identity);
ClickableTile ct = tile.GetComponent<ClickableTile>();

Something i am missing?

I assume your “ClickableTile” script has just been added (as a component) to a standard GameObject that you’ve turned into a prefab, right? if that’s the case, the object you’re instantiating isn’t a “ClickableTile”, it’s a GameObject that has a ClickableTile component attached to it.

To get access to the ClickableTile script, you need to instantiate the prefab as a GameObject, and then get a reference to the ClickableTile component. So, something like this:

GameObject tile = (GameObject)Instantiate(tt.tileVisualPrefab, new Vector3(x, y, 0), Quaternion.identity);
var ct = tile.GetComponent<ClickableTile>();