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!

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);

You can set the game object’s parent directly on instantiation:

GameObject enemy = GameObject.Instantiate(enemyPrefab,, Quaternion.identity, GameObject.FindGameObjectWithTag("Canvas").transform);