Search code examples
c#unity-game-engineperspectivecameragameobject

Gameobject instantiated in canvas shows up behind other canvas items


In my game, if it is the first time the player has ever played the game then I have an image that is displayed. I instantiate it in the canvas like so:

    if (PlayerPrefs.GetInt("First Time", 1) == 1)
    {
        introEnabled = true;

        //pause all activity
        pause.pauseOrResume();

        intro = Instantiate (Resources.Load ("intro"), transform.position, Quaternion.identity) as GameObject;
        Canvas canvas = GameObject.Find("Canvas").GetComponent<Canvas>();
        intro.transform.SetParent(canvas.transform, false);
        //robot = Instantiate (Resources.Load ("robot"), transform.position, Quaternion.identity) as GameObject;

        PlayerPrefs.SetInt("First Time", 0);
        PlayerPrefs.Save();
    }

I can see in the inspector when the game is running that when the object is created, it does show up in the canvas. I just have no idea why it won't show up on top of all of the other objects in the canvas.

The canvas rendering mode is set to "Screen space - Overlay" and it is set to 0 in the sort order. The game object being instantiated also has a sort order of 0 and it is in the default layer.

Nothing I have tried has worked. The z values make no difference and even putting the canvas and the instantiated object in the Default layer and setting the canvas to a sort order of 2 and the instantiated object to a sort order of 1 (so it is rendered first) does not make a difference.


Solution

  • What you want is to use transform.SetAsLastSibling() . The CanvasRenderer renders the GameObjects in order according to their sibling index's (position in the hierarchy), from top to bottom.

    However, after examining your code further I noticed something and I should say that if you are trying to instantiate the intro screen, I would highly recommend to instantiate it with it's own Canvas, instead of parenting it to the existing one. Something that significant should have it's own dedicated Canvas.

    Update: The problem here is that you are instantiating GameObjects with a transform and Sprite renderer. Canvas UI gets rendered last, over all mesh layers, so if you want your newly instantiated GameObjects to participate, they will need to have RectTransform and Image components instead.