- Home /
How to get ARGB values from Texture object?
I have a simple 2-triangle mesh (a quad) which I'm applying a texture to. Basically a sprite. I'm still using Unity 3.5.7.
Attached to this mesh object is a script. In the script, I want to access
this.renderer.material.mainTexture
The Type of the object sitting at this property is "UnityEngine.Texture".
I want to get all of the pixels in this Texture as a flattened (or 2d) array of ARGB values. I do not need single-pixel access, but rather access with a method like "GetPixels32()". However, the Texture class doesn't have such a method, the Texture2d class does.
An overriding requirement for this project is that I must minimize package size (mobile app), so I am very hopeful I don't have to enable "read/write" on the texture.
My current solution, which is unacceptable, is that I have one texture tied to the material that shows up in the GUI/Editor, and a second (possibly different) texture assigned to a Texture2d Property on the script. That second texture has "read/write" enabled. This is functionally accurate, but is horrible design (2 textures for the one purpose) and requires extra memory (for read/write enabled)
Does someone with deep Unity knowledge have a solution that would (a) allow me to leave "read/write enabled" OFF AND allow me to get all pixels in a Texture (not a Texture2d) as a flattened array of ARGB values?
Thank you so much for any help you may be able to offer!
Answer by Eric5h5 · Mar 25, 2014 at 04:43 AM
Just cast renderer.material.mainTexture to Texture2D. You do need read/write enabled...if you want to read a texture, there's obviously no alternative. But there's no reason to use two textures.
Can't do that- The object is of type Texture, as is the property "mainTexture" on material. Texture2d derives FRO$$anonymous$$ Texture. You cannot cast "up" like that in C#, and only dangerously so in C++.
If the object at renderer.material.mainTexture were of type Texture2d, then I could cast that Texture property as you suggest. But it isn't. The object AND the property are both of of type UnityEngine.Texture. There's no language-level casting that can be done.
$$anonymous$$y hope is that someone knows a method around this. $$anonymous$$y next step is to use Reflection at run-time to figure out what is available on Texture as "private" fields/methods. I would prefer to avoid that, but I gotta do what I gotta do.
Thanks, though!
Yes you can. You're massively overcomplicating this.
Texture2D myTex = renderer.material.mainTexture as Texture2D;
var pix = myTex.GetPixels32();
Your answer
Follow this Question
Related Questions
Setting pixels on a texture? 2 Answers
Draw one texture on to another? Get Set Pixels. 0 Answers
Merging Textures At Runtime - Not Correct? 1 Answer
GetPixels of RenderTexture 3 Answers
GUI texture to change texture when hovered over or clicked? 2 Answers