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.
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?
Answer by ansjuan · Nov 29, 2021 at 09:31 AM
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...