- Home /
How do I generate mipmaps at runtime?
How do I generate mipmaps at runtime for a texture which is loaded using the WWW class? I can load this texture at runtime and apply it to a material, but mipmaps aren't automatically generated. Does Unity have a runtime function to do this, or will I have to create my own script to generate mipmaps using SetPixels?
Answer by duck · Jan 17, 2010 at 09:40 PM
Having skimmed the docs, I can't see a built in method to do this. Perhaps you could make use of the fact that "Apply()" auto-generates mipmaps by default.
Try myTexture.Apply();
on its own after getting the texture first. If that doesn't work you could venture into 'ugly hack' territory by trying this to force a draw using SetPixels which would then hopefully make 'apply' do its thing (just a guess, untested & may not work!):
myTexture.SetPixels( myTexture.GetPixels(0,0,myTexture.width,myTexture.height) );
myTexture.Apply();
If that doesn't work, it may be that there's something different about WWW.texture, and perhaps you have to use WWW.LoadImageIntoTexture to load the image into an existing Texture2D rather than just using WWW.texture directly (and perhaps even try the above things on the texture afterwards).
Using Texture2D.SetPixels(Texture2D.GetPixels()) works great. Thank you.
Specifically, this must be done on a fresh texture, so the actual code will end up looking a little more like this:
var tex1 = www.texture; var tex2 = new Texture2D(tex1.width, tex1.height); tex2.SetPixels(tex1.GetPixels()); tex2.Apply(true);
Answer by Eric5h5 · Jan 17, 2010 at 09:42 PM
Create a texture first that has mipmaps, then use WWW.LoadImageIntoTexture.
Note that the texture you create must have mipmapCount >= 2. So if you create a 1x1 dummy texture with mips and pass it to WWW.LoadImageIntoTexture, you will be sad.
Answer by gwfuserPS · Sep 14, 2015 at 11:41 PM
Set the 4th parameter to true it will enable the mipmap.
Texture2D(int width, int height, TextureFormat format, bool mipmap, bool linear)
Answer by denevraut · May 25 at 02:54 PM
I found this solution for me, all the others gave me errors (unity 2019.2)
Hope it can help you !
var dstTex = Texture2D(srcWidth, srcHeight, srcFormat, true);
Graphics.CopyTexture(srcTex, 0, 0, 0, 0, srcWidth, srcHeight, dstTex, 0, 0, 0, 0);
dstTex.apply(true);
References:
https://docs.unity3d.com/2019.2/Documentation/ScriptReference/Graphics.CopyTexture.html
Graphics.CopyTexture(Texture src, int srcElement, int srcMip, int srcX, int srcY, int srcWidth, int srcHeight,
Texture dst, int dstElement, int dstMip, int dstX, int dstY);
https://docs.unity3d.com/2019.2/Documentation/ScriptReference/Texture2D-ctor.html
Texture2D(int width, int height, TextureFormat textureFormat, bool mipChain);
Your answer
