Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is it possible to add a render texture to a gameObject through a script?

What Ive been trying to do is create a camera, a cube, and take what the camera sees and display it on the cube. I would like to do all of this through a single script, where I instantiate a cube and camera prefab, and from there I do the connection between the two.

So far, Ive managed to create both of these objects, and Ive created a render texture, which is assigned to the camera:

GameObject cubo = Instantiate(cuboprefab);
            GameObject camara = Instantiate(prefabCamara);
            cubo.transform.position = new Vector3(0, 0, 0);
            camara.transform.position = new Vector3(0, 0.5f, 3);
            rt = new RenderTexture(256, 256, 16, RenderTextureFormat.ARGB32);
            rt.useDynamicScale = true;
            rt.Create(); 
            var compcam = camara.GetComponent<Camera>();
            compcam.targetTexture = rt;
            //cubo.GetComponent<Renderer>().sharedMaterial = rt;

The last line is commented because thats where my issue is, I cant seem to find a way to assign a RenderTexture object to the material, even though it is something that you can do with the Unity UI.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You are currently trying to assign a material, not the texture of the material. Set the texture to the mainTexture property of the material instead.

cubo.GetComponent<Renderer>().sharedMaterial.mainTexture = rt;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading