mariusz_witeczek
mariusz_witeczek

Reputation: 115

Draw 3D GameObject above GUI in Unity

I would like to draw a GameObject in front of all other components in my project and GUI Textures as well.

I created a second Camera and set Depth and Layer but it still not work. I hope you can help me to find the error or something I forgot.

Here is my MainScript which is drawing a simple Texture:

using UnityEngine;
using System.Collections;

public class MainScript : MonoBehaviour
{
Texture2D texture;

// Use this for initialization
void Start()
{
    texture = new Texture2D(Screen.width, Screen.height);

    for (int y = 0; y < texture.height; y++)
    {
        for (int x = 0; x < texture.width; x++)
        {
            texture.SetPixel(x, y, Color.blue);
        }
    }
    texture.Apply();
}

void OnGUI()
{
    GUI.DrawTexture(new Rect(0, 0, texture.width, texture.height), texture);
}
}

I also created two cameras and a GameObject which displays a GUI Texture. The Texture is visible in the preview screen but on runtime the Texture which is drawing in the MainScript is foregrounded.

I made two more Screenshots of my Camera Objects. See here:

enter image description here

enter image description here

I can also supply the whole project for you. It is just a basic test project.

Here is the link to the Project in Google Drive: Download

Upvotes: 3

Views: 8686

Answers (2)

Roberto
Roberto

Reputation: 11933

You cannot draw 3D objects in front of the GUI elements, OnGUI code always renders in top of everything.

To achieve this you can use Render Textures (Unity Pro only): have two cameras in your scene, place your 3D objects in one camera, render this camera to a texture, and finally use that texture as the source of a GUI.DrawTexture().

Upvotes: 0

sebastian s.
sebastian s.

Reputation: 160

set depth of camera2 to camera1.depth+1, Clear Flags of camera2 to depth only and Clear Flags of camera1 to skybox. Uncheck GUILayer at Camera2 and check GUILayer in camera1. That should do it...

enter image description here

enter image description here

enter image description here

Upvotes: 1

Related Questions