create Render Textures at runtime
Hello there,
I'm wondering if anyone can help me. I am bit lost and haven't been able to find any information that could help me here or anywhere on the internet.
I want to create several CCTVs at runtime. This is because I may need to create 10 or 50 or 25 CCTVs or "screens" depending on the outcome of the gameplay.
So, I read it was possible to create Render Textures at runtime. I am using c#.
Here's what I have tried:
public GameObject CCTVScreenPrefab; //Prefab Added via the Inspector
public GameObject CaptCamPrefab; //Camera Prefab Added via the inspector
void Start ()
{
GameObject CCTVScreen = Instantiate(CCTVScreenPrefab) as GameObject;
GameObject CaptCam = Instantiate(CaptCamPrefab) as GameObject;
//Creating a render texture at runtime:
RenderTexture RefTexture = new RenderTexture(256, 256, 24, RenderTextureFormat.ARGB32);
RefTexture.Create(); // Not sure if I really need this.
//Linking everything:
CaptCam.GetComponent<Camera>().targetTexture = RefTexture ;
CCTVScreen.GetComponent<Material>().SetTexture("_MainTex", RefTexture);
//I tried this too: CCTVScreen.GetComponent<Material>().mainTexture = RefTexture;
But it won't work. What am I doing wrong? I really don't want to create 50 render textures on the scene if I don't need them. Just the number of cameras and the number of render textures and the number of "screens" or objects to display such texture at runtime.
I tried the standard shader as a material for all these objects or "screens". Ideally, the mobile/diffuse shader would be better as the simulation is for mobile phones and tablets.
I am also using at the moment Unity 5.2 Personal. For what I have researched, Render Texture is available for Unity versions greater than 5.0.
Thank you very much for your help.
Hello. did u find the solution for your problem, is so please share the example code?
Answer by Bunny83 · Mar 22, 2018 at 02:50 AM
This line:
CCTVScreen.GetComponent<Material>().SetTexture("_MainTex", RefTexture);
doesn't make much sense as Material is not a Component. What you want to do is accessing the Renderer of the screen object and change the texture of the material of the Renderer
CCTVScreen.GetComponent<Renderer>().material.mainTexture = RefTexture;