0
votes

I have two renderer objects (A and B) in my scene connected to two different cameras (green square and red square):

Camera Example

I am using the following script on both render objects to create a render texure on the corresponding camera and then draw this as a texture on the object on each frame:

using UnityEngine;
using System.Collections;

[ExecuteInEditMode]
public class CameraRenderer : MonoBehaviour 
{
    public Camera Camera;
    public Renderer Renderer;

    void Start()
    {
        RenderTexture renderTexture = new RenderTexture (256, 256, 16, RenderTextureFormat.ARGB32);
        renderTexture.Create ();
        Camera.targetTexture = renderTexture;
    }

    void Update () 
    {
        Renderer.sharedMaterial.mainTexture = GetCameraTexture ();
    }

    Texture2D GetCameraTexture()
    {
        RenderTexture currentRenderTexture = RenderTexture.active;
        RenderTexture.active = Camera.targetTexture;
        Camera.Render();
        Texture2D texture = new Texture2D(Camera.targetTexture.width, Camera.targetTexture.height);
        texture.ReadPixels(new Rect(0, 0, Camera.targetTexture.width, Camera.targetTexture.height), 0, 0);
        texture.Apply();
        RenderTexture.active = currentRenderTexture;
        return texture;
    }
}

I am expecting to see two different images on A and B from the different cameras, but I am seeing the same image. I originally was using a render texture that I created in the editor attached to the camera, but though that might be what was causing them to render the same thing so I tried creating a new texture on each object. Sadly this still resulted in the same outcome.

I'm pretty new to unity so I've run out of ideas pretty fast - any suggestions would be great!

2

2 Answers

2
votes

I wouldn't advise naming your objects your class names. Anyways I think the renderers are using the same material and they both render the same texture whichever camera gives them last.

Either use Renderer.material to automatically create an new instance of the material, or manually assign different materials to the 2 renderers.

2
votes

Try,

Renderer.material.mainTexture = GetCameraTexture ();

Instead of,

Renderer.sharedMaterial.mainTexture = GetCameraTexture ();