Assign render texture to camera - Unity

Viewed 636

Hi I'm learning to make a Audio Visualiser in Unity. The problem i'm facing is that I have a button, when clicked will programmatically load another scene at runtime, (call it scene Phyllo) Phyllo has a camera. Now there's also a "main" scene, call it UI_v15. I have put Phyllo's camera view into a render texture. In UI_v15, I have a Cube GameObject, i want to assign Phyllo's render texture to the cube, so that when the aforementioned button is pressed, the Cube can display the camera view from Phyllo. But this is where I failed...

Phyllo

What happened instead is I'm just getting the view from Phyllo like this (I'm just getting the full view from Phyllo). What instead should happen is the view should be rendering into the Cube I talked about earlier.

When the program runs, the targetTexture for Phyllo's camera is not assigned a texture, which it should. As show here in the red part

This is the method that gets called when the button (inside UI_v15) is pressed.

public void SelectVisualiser()
{

    string sceneName = GetComponent<Button>().GetComponentInChildren<Text>().text;
    print("scene name " + sceneName);
    SceneManager.LoadScene(sceneName, LoadSceneMode.Additive);
    VisualiserManager.instance.LoadVisualiser(sceneName);
}
              
public void LoadVisualiser(string name)
{
    //the script PhylloCamera is attached to PhylloCamera in the Phyllo scene.
  
    Camera cam = PhylloCameraRef.instance.phylloCam;
    Material mat = new Material(Shader.Find("Standard"));
    RenderTexture rt = CreateTexture();
    mat.SetTexture("_MainTex", rt);
    cam.targetTexture = rt;
    display.GetComponent<MeshRenderer>().materials[0] = mat;

}

the class PhylloCameraRef is attached to the scene Phyllo,which can be loaded at at runtime.

    public class PhylloCameraRef : MonoBehaviour
{
    public Camera phylloCam;
    public static PhylloCameraRef instance;

    
    void Start()
    {
        if (instance is null)
        {
            
            instance = this;
            //getting camera
            phylloCam = gameObject.GetComponent<Camera>();
        }
    }
}

Does anyone know why Phyllo's camera is not rendering into the Cube? Thanks.

EDIT: Below is the code for CreateTexture()

public RenderTexture CreateTexture()
{
    RenderTexture rt = new RenderTexture(256, 256, 16, RenderTextureFormat.ARGB32);
    rt.Create();
    return rt;
}

I forgot to add, for some unknow reason, the camera's targetTexture in UIv_15 is assigned the render texture. The cube is an actual 3D gameObject.

0 Answers
Related