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

Shader doesn't have a texture property '_MainTex'

The wacky thing is I ran my code once and it worked like a charm. The line of code I’m getting the error on is:

exampleTexture = (Texture2D)rend.material.mainTexture;

I know that the custom shader I’m using has something other than ‘mainTexture’, it’s something along the lines of:

Properties
    {
        _Example ("Example (R16)", 2D) = "black" {}
        _Color ("Color", Color) = (1, 1, 1, 1)
    }

I’m just stumped as it worked the first time, any ideas?

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 :

Well if you look into Material.mainTexture and also the source code you can see that there are two things this can refer to

  • Either you have a shader property which is attributed with [MainTexture]
  • or as fallback it is looking for _MainTex.

Or in the word of the API

By default, Unity considers a texture with the property name "_MainTex" to be the main texture. Use the [MainTexture] ShaderLab Properties attribute to make Unity consider a texture with a different property name to be the main texture.

Both is not the case in your shader.

You would probably want to rename Example to

_MainTex ("Example (R16)", 2D) = "black" {}

or if you want/need to stick to the name _Example you will need to add the mentioned attribute

 [MainTexture] _Example ("Example (R16)", 2D) = "black" {}

Or alternatively do not use the default property accessors but rather use the more generic Material.GetTexture

exampleTexture = (Texture2D)rend.material.GetTexture("_Example");
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