Set renderCamera in renderMode 'Screen Space - Camera' from code?

Im trying to instantiate Canvas prefabs on running time, and I want the Canvas to have RenderMode ‘Screen Space - Camera’.

Other than that, I have a separate GuiCam (Camera) in the scene, and I want to set it as the renderCamera for the instantiated canvas. I cant seem to find a way that works for me, to do this from code.

I’m using C#.

Q: How do you set renderCamera on a Canvas from code? Do you have any suggestions? :slight_smile:

the canvas class should have a .renderMode which you can set as the Canvas.RenderMode.ScreenSpaceCamera.

Same goes for the camera there is the worldCamera you can set.

I doesn’t work for me, and I cant find anything in the documentation local. Do I need a certain library? Im using 4.6.20b.

you’ll have to show a code snippet to what you’re doing as both those functions on the canvas have been around since very early betas if not alpha.

Oki I’ll try. There is a good chance, that there is something fundamental I’m just not aware of. The following code is attached to the canvas I’m instantiating runtime.

The canvas has RenderMode ‘Screen Space - Camera’, and I want to set the renderCamera for this canvas to cam in the code.

But I cant find Canvas.Rendermode, og canvas.rendermode.‘something’.

private Camera cam;

    // Use this for initialization
    void Start ()
    {
        Canvas canvas = gameObject.GetComponent<Canvas>() ?? null;
        cam = GameObject.FindGameObjectWithTag("GuiCamera").camera;
        if(canvas != null)
        {
        // Set canvas' renderCamera to cam
        }
        else print ("derp!");

    }

So i just copied your script into a new script in a blank project and was able to do the following with help from autocomplete.

private Camera cam;

    // Use this for initialization
    void Start()
    {
        Canvas canvas = gameObject.GetComponent<Canvas>();
        cam = GameObject.FindGameObjectWithTag("GuiCamera").camera;
        if (canvas != null)
        {
            canvas.renderMode = RenderMode.OverlayCamera;
            canvas.worldCamera = cam;
        }

    }
5 Likes

Oh, I have tried the second line of yours, but didn’t new I needed to do the first. Thanks for the help, Ill appreciate it!

i dont know if you need to do the first or not. If you already have set the canvas in the inspector to “Screen Space - Camera” then you shouldnt need to.

11 years later and this was still super helpful!