- Home /
How to use TileMap.GetInstantiatedObject?
I painted a GameObject on Tilemap with PrefabBrush.Now,I want get this GameObject.So, I use the function "TileMap.GetInstantiatedObject" and Debug it . But ,the result is Null.Here is My Code.
private Grid grid;
public GameObject Dirt;//drag to Inspector. the position is (-2.5,-1.5,0)
public TileMap Background;//drag to Inspector
private void Start()
{
grid = transform.GetComponent<Grid>();
Vector3Int pos = grid.WorldToCell( Dirt.transform.position );
Debug.Log(pos);//(-3,-2,0)
Debug.Log( Background.GetInstantiatedObject(pos));//=> result is null
}
Blockquote
I also tried to change the Dirt's position to (-3,-2,0) In Inspector. But,It's still Null.
I don't feel quite knowledgeable enough to post a full-blown answer, but my experience has been that the object is instantiated after Start()
runs on the parent. I suspect that in the next frame (maybe in Update()
) you can call GetInstantiatedObject(pos)
and get the result you're expecting.
Answer by gubbi · May 29, 2020 at 07:00 PM
Late answer, but for others:
Gameobjects are instantiated some time after Start() runs, and before the first frame (before Update is first called). try GetInstantiatedObject from Update instead.
One dirty solution is to create an Init-method which runs on the first frame like this:
private void Update() {
if (!_inited) {
_inited = true;
Init();
}
}
private void Init() {
...
tilemap.GetInstantiatedObject(c3)
}
This seems to be broken in 2019.4.0f1 though ...
Thanks for the tip! Indeed, this was bugging the heck out of me. Working on 2019.4.35 and can confirm that in Start()
I get a null
value for the game object. Instead of your solution, I used a coroutine which only needs to wait until the very first frame ends. Like so:
private void Start()
{
StartCoroutine(InitTilemapObjects());
}
IEnumerator InitTilemapObjects()
{
// Wait a single frame for the tilemap to finish instantiating
yield return new WaitForEndOfFrame();
GameObject instObject = GroundTilemap.GetInstantiatedObject(new Vector3Int(0, 0, 0));
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612190017im_/https://answers.unity.com/themes/thub/images/avi.jpg)