简体   繁体   中英

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:

在此处输入图片说明

在此处输入图片说明

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

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...

在此处输入图片说明

在此处输入图片说明

在此处输入图片说明

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() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM