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;
Debug.Log(tile);
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()
{
Debug.Log("Click!");
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?
Answer by jgodfrey · May 21, 2016 at 03:24 PM
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>();
Yes that is the case. I was assu$$anonymous$$g i could just cast it to a ClickableTile, i am sure i saw something like this in a tutorial i watched earlier. Well, thanks, i guess that is cleared up.