You are setting properties of the components on the referenced gameObject, you need to wait for the instance to be created first. Most of this logic should be done in StartUp(). GetTileData should only return data about the tile.
See the following as an example:
AnimatedStaticPrefabTile.cs
/*
* Delve : Scripts.Tiles.Advanced - Dan Flanigan, 2019
*/
using General;
using UnityEngine;
using UnityEngine.Serialization;
using UnityEngine.Tilemaps;
// ReSharper disable once CheckNamespace
[CreateAssetMenu]
public class AnimatedStaticPrefabTile : AnimatedTile
{
//public Sprite TileSprite;
[FormerlySerializedAs("TileAssociatedPrefab")] public GameObject tileAssociatedPrefab;
[FormerlySerializedAs("PrefabLocalZOffset")] public float prefabLocalZOffset;
[FormerlySerializedAs("UseAbsoluteZOffset")] public bool useAbsoluteZOffset;
[FormerlySerializedAs("PrefabAbsoluteZOffset")] public float prefabAbsoluteZOffset = -1f;
public override bool StartUp(Vector3Int position, ITilemap tilemap, GameObject go)
{
//This prevents rogue prefab objects from appearing when the TileBase palette is present
#if UNITY_EDITOR
if (go != null)
{
if (go.scene.name == null)
{
DestroyImmediate(go);
}
}
#endif
if (go != null)
{
if (useAbsoluteZOffset)
{
//Modify position of GO to match middle of TileBase sprite
go.transform.position = new Vector3(position.x + Globals.PrefabXyOffset
, position.y + Globals.PrefabXyOffset
, prefabAbsoluteZOffset);
return true;
}
//Modify position of GO to match middle of TileBase sprite
go.transform.position = new Vector3(position.x + Globals.PrefabXyOffset
, position.y + Globals.PrefabXyOffset
, position.z);
//Set Z
var localPosition = go.transform.localPosition;
localPosition =
new Vector3(localPosition.x, localPosition.y, prefabLocalZOffset);
go.transform.localPosition = localPosition;
}
return true;
}
public override void GetTileData(Vector3Int position, ITilemap tilemap, ref TileData tileData)
{
tileData.sprite = !Application.isPlaying ? m_AnimatedSprites[0] : null;
if (tileAssociatedPrefab && tileData.gameObject == null)
{
tileData.gameObject = tileAssociatedPrefab;
}
tileData.flags = TileFlags.InstantiateGameObjectRuntimeOnly;
}
}