Dynamically instantiated game objects not showing in main camera (with background camera)

Hi all,

I have followed the instructions here to create a background image in a second camera. The main camera is set to ignore the background layer (culling mask has everything except background), and the background camera is set to only see the background image (only background is set in culling mask).

My code instantiates many game objects dynamically. These are not visible in my scene - it looks like they are behind my GUITexture because when I click run in the editor I can see them in the scene window, just not in the game window.

Any ideas?

you should put your new objects into its layer. like this:

gameObject.layer = 5; // 5 is the number of its layer

I have done some more testing, and this seems to be an editor quirk/bug.

For example, quitting and restarting Unity resolves this issue - until I change the scene view (e.g. zoom in/out), after which it stops working again. Making an unrelated code change in a script then fixed it again. And so on...

I am using Unity Free (2.6) on Windows Vista.

In the mean while, if you want to try another way while you're designing the game - try creating this C# script (CreateBGPlaneOnCamera.cs) and attaching this to your BG camera. Set nBackgroundLayerID to the BG layer number, and assign a texture to txBackground. It should get ya there quick and dirty.

When you're ready to stop playing around, just return to using the GUILayer approach, since I don't think that quirk/bug will happen in a built player.

using UnityEngine;
using System.Collections;

public class CreateBGPlaneOnCamera : MonoBehaviour 
{
    public Texture2D    txBackground;
    public int          nBackgroundLayerID;

    void Start () 
    {
        GameObject plane = GameObject.CreatePrimitive(PrimitiveType.Plane);
        plane.renderer.material.shader = Shader.Find("Transparent/VertexLit");
        plane.renderer.material.color = new Color(0.5f, 0.5f, 0.5f, 1f);
        plane.renderer.material.SetColor("_Emission", new Color(0.5f, 0.5f, 0.5f, 1f));
        plane.renderer.material.mainTexture = txBackground;
        plane.gameObject.layer = nBackgroundLayerID;
        plane.transform.parent = transform;
        plane.transform.localScale = new Vector3(Screen.width * 0.1f, 1f, Screen.height * 0.1f);
        plane.transform.localRotation = Quaternion.Euler(-90f, 0f, 0f);
        plane.transform.localPosition = new Vector3(0f, 0f, Screen.height * 0.5f / Mathf.Tan(camera.fov * 0.5f * Mathf.Deg2Rad));
        camera.farClipPlane = plane.transform.localPosition.z;
    }
}