Skip to main content
2 of 2
added 316 characters in body
o.o
  • 191
  • 4
  • 12

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:

enter image description here

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!

This is what it looks like when it creates it in-game: Enemy_Orange3(Clone) is created outside of the canvas and at the bottom left instead of the center. My camera is in the same position and is the same size of the canvas.

enter image description here

o.o
  • 191
  • 4
  • 12