Instantiating a image as a child of a canvas in Unity 5.3

3.4k Views Asked by At

I'm trying to instantiate an Image as a child of a canvas element.

This code is attached to the Unity Canvas that i want to have as the parent.

 Image Pokal = GameObject.Instantiate(Resources.Load("Pokal")) as Image;

    if (Pokal != null)
        Pokal.gameObject.GetComponent<RectTransform>().parent = gameObject.transform;

I want my "Pokal" to become a child of the UI Canvas element. How do i do this? The prefab is added to the scene but i can't figure out how to make it a child of the Canvas Element.

2

There are 2 best solutions below

0
On

I believe that this question has already been answered before. Anyway, all you have to do is to get the canvas. You are setting the parent to an empty gameobject not the actual canvas.

public GameObject myCanvas; // you also can do GameObject.Find (CanvasName)
Image Pokal = GameObject.Instantiate(Resources.Load("Pokal")) as Image;

    if (Pokal != null)
        Pokal.transform.parent = myCanvas.transform;
0
On

I hope this will help you to solve your problem.

Image Pokal = Instantiate(Resources.Load("Pokal")) as Image;

if (Pokal != null)
    Pokal.transform.parent = transform;