Instantiate Prefab From Script Inside A Canvas
I am trying to instantiate a Prefab inside a Canvas. Right now, it keeps appearing behind the canvas. I was reading online and it said to set the parent of the GameObject you are trying to instantiate. However, I can't figure out how to get the Canvas component.
My hierarchy looks like this:
My EnemyFormation object has this script attached to it:
public class EnemySpawner : MonoBehaviour {
public GameObject enemyPrefab;
void Start () {
Instantiate(enemyPrefab, new Vector3(0, 0, 0), Quaternion.identity);
Debug.Log("Spawning enemy");
}
}
I attach the prefab inside Unity editor. I tried adding this line under Instantiate():
enemyPrefab.transform.SetParent(GameObject.FindGameObjectWithTag("Canvas"), false);
However, I get an error saying it can't convert from Unity.GameObject to Unity.Transform.
How do I make the prefab appear inside the Canvas instead of behind it? Thanks in advance!
Answer by MyI · Aug 09, 2016 at 06:11 AM
Figured it out. I had to use another GameObject to set the parent:
GameObject enemy = Instantiate(enemyPrefab, new Vector3(0, 0, 0), Quaternion.identity) as GameObject;
enemy.transform.SetParent (GameObject.FindGameObjectWithTag("Canvas").transform, false);
Answer by rockbyte · Nov 04, 2018 at 04:45 PM
You can set the game object's parent directly on instantiation:
GameObject enemy = GameObject.Instantiate(enemyPrefab, Vector3.zero, Quaternion.identity, GameObject.FindGameObjectWithTag("Canvas").transform);
This is the preferred way as per this link: https://github.com/JetBrains/resharper-unity/wiki/Avoid-using-Object.Instantiate-without-%E2%80%9CTransform-Parent%E2%80%9D-parameter-and-using-SetParent-later
Ideally you would already have a reference to the Canvas from earlier to avoid that call to FindGameObjectWithTag in the Instantiate.
Your answer
Follow this Question
Related Questions
Objects disappear on resolution change 1 Answer
Changing a Prefab's Text component seems to be broken. 1 Answer
Calling function to update variable from prefab script not working as intended 0 Answers
Does using multiple World Space Canvases affect performance? 0 Answers
Adding prefab object on collision to a another script 0 Answers