I've been following the LearnOpenGL tutorials and I've come across a piece of code I don't understand.

glUniform1i(glGetUniformLocation(ShaderID, "textureVar"), 0);

In the above code ShaderID is a GLuint which references a shader.

textureVar is a sampler2D in the shader.

I don't understand the last parameter in that line of code. Does the 0 represent GL_TEXTURE0 or what exactly does the last parameter mean?


Yes, the 0 in there represents the texture unit that the sampler references. So in order for a texture to be referenced by textureVar in the shader, it should be bound to texture unit 0 (e.g. by glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, ...) or any other means you can bind a texture to a texture unit.

However, note that it doesn't actually matter which texture unit is active when setting that uniform, nor what texture is bound to that unit. Effectively to the outside world the sampler uniform is just an integer value specifying the texture unit to take its texture and sampler information from. It can be set to that texture unit whenever you want and the texture can be bound to that unit whenever you want (in fact in GLSL 4.20+ you can actually initialize the uniform right in the shader with e.g. layout(binding=0) uniform sampler2D textureVar). All that matters is that at the point the shader gets invoked (i.e. when actually glDraw...ing something) the sampler is set to the proper unit and the texture is bound to that unit.

For more information on the matter, take a look at the corresponding section in the OpenGL Wiki.


As was stated by @PaulHK, the last parameter represents the Texture Unit the texture is bound to.

For example:

GLuint unit = 0;

glActiveTexture(GL_TEXTURE0 + unit);
glBindTexture(GL_TEXTURE_2D, texture);
glUniform1i(glGetUniformLocation(shaderRef, "texture1"), unit);

unit = 1;

glActiveTexture(GL_TEXTURE0 + unit);
glBindTexture(GL_TEXTURE_2D, texture2);
glUniform1i(glGetUniformLocation(shaderRef, "texture2"), unit);

The above code binds Texture Unit 0 to the fragment shader and then sends it texture1. Then it binds Texture Unit 1 to the shader and sends it texture2. The unit var represents the Texture Unit we are binding to the sampler in the shader to.

  • $\begingroup$ @NicolBolas open.gl/textures states that samplers in the fragment shader are bound to texture units so wouldn't it make sense to use GL_TEXTURE0 and so on to make the code more readable $\endgroup$ – Archmede May 6 '17 at 16:33
  • $\begingroup$ @NicolBolas Does my answer look correct now? $\endgroup$ – Archmede May 6 '17 at 17:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.