Convert Texture to Texture2D e.g. renderer.material.mainTexture

How do you convert renderer.material.mainTexture - a texture - to a texture2d?

I’m sorry Ina, I don’t have an answer for you, but I do have the same problem I think. After searching all over the place, this is the only real posting I’ve found even relating to this subject.

Just a little background on my issue: I’m an artist (yeah, I know) who used java scripting to make a basic game in unity, and recently purchased everything to actually get to work on an iPod Touch. But when I switched over my build to work with iOS I started getting this error and many others, but this one refuses to be fixed easily. Here’s a look at my script:

I’m assigning a texture to the “Level_Tester” gameObject in another script, then calling this function to recall the texture and build the level function:

BuildLevel ()


    var texture : Texture = GameObject.FindWithTag("Level_Tester").renderer.material.GetTexture("_MainTex");

    var ReadInLevel = texture.GetPixels(0);

    //use the pixel information as a guide to place objects on a 2d plane


So after switching to an iOS build, this no longer compiled - saying that “GetPixels” isn’t a function of “Texture”. So I switched my script to “var texture : Texture2D”, and while this version does compile - I get the warning "Implicit downcast from ‘UnityEngine.Texture’ to ‘UnityEngine.Texture2D’. Of course running the game doesn’t allow the texture to load and causes other issues. I tried flipping back to PC and Mac standalone and having “Texture2D” as my variable type and I’m having a whole new pile of issues.

I think I’m understanding generally that downcasting is bad, but I can’t seem to find my way around it. Any suggested reading or specific help out there?

If the texture you want to access already is a Texture2D (in a Texture variable), you can use something like this:

Texture2D thisWillContainTextureIfItWasA2DTexture;
if (tex is Texture2D) thisWillContainTextureIfItWasA2DTexture= (tex as Texture2D);

But if the Texture that is being used is a RenderTexture, you can copy its contents to a Texture2D, using ReadPixels. Keep in mind that for ReadPixels to work, the texture you copy it to must be in the ARGB32 or the RGB24 TextureFormat, and the RenderTexture must have RenderTextureFormat ARGB32. Phodges posted an example of copying RenderTextures below.

EDIT: As mentioned below, if the object is already of a castable type then you should most certainly do that.

Rather than cast, you can read a RenderTexture into a Texture2D object. Switch the RenderTexture you want to active and then proceed as in this snippet:

RenderTexture was =; = <target render texture>;
// width and height, chosen to match the source r.t.
Texture2D tex = new Texture2D(width, height, TextureFormat.ARGB32, false);
// Grab everything
tex.ReadPixels(new Rect(0f,0f,width,height), 0,0);
tex.Apply(); = was;