How do I assign a render texture as a target texture to a camera from script?

I have a script that creates an empty render texture in which a camera will render to.
The render texture is saved in the assets folder.

RenderTexture rt;
Camera mycamera;
rt = new RenderTexture(512, 512, 16, RenderTextureFormat.ARGB32);
rt.Create();
Debug.Log("rt done !");
AssetDatabase.CreateAsset(rt, "Assets" + "/toto"+ ".rendertexture");

In the editor, all I have to do is pick the target texture in the camera component and select the toto.rendertexture in the asset folder. Easy peasy.

171876-rendertexture.png


But for the life of me, I can’t find how to do the same thing with a C# script.
I tried all sorts of combos with the following line below.

mycamera.targetTexture = rt;

But the target texture in the camera component still seems to be “none”.
I tried adding this line to no avail.

rt = Resources.Load<RenderTexture>( "toto_"+ND2.ToString()+".rendertexture" );

or

RenderTexture.active = rt;

I am out of ideas ATM.

Did I miss something embarrassingly obvious?

Hello,

I have exactly the same doubt and I am getting the same error, did you solve it somehow? I cannot assign a render texture by script…

Hi there,
I had the same issue where I could not assign another render texture to my cameras in runtime. As a result, I searched the internet for answer and stumbled across this and it seemed like nobody had a solution.
Thankfully, I found one! In my case I tried to assign the rendertexture in the start function. This didn’t work, so I tried to put the code in a seperate function and then invoke that function with a tiny delay, and that worked like a charm! I hope this helps :slight_smile: