How to update shader code outside the shader in a for-loop with glGetUniformLocation() and glUniform3f()?

Hi, I am trying to do this learnopengl tutorial (HDR):

I saw that they used the following for-loop to update the variables in the shader code:

    for (unsigned int i = 0; i < lightPositions.size(); i++)
        shader.setVec3("lights[" + std::to_string(i) + "].Position", lightPositions[i]);
        shader.setVec3("lights[" + std::to_string(i) + "].Color", lightColors[i]);

Now, I want to know if this is also possible by using glGetUniformLocation() and glUniform3f(). I tried this (first, just with the lightPositions and using an array instead of a vector):

int size = sizeof(lightPositions) / sizeof(float3);
  for (unsigned int i = 0; i < size; i++)
    int pos_loc = glGetUniformLocation(light_program_handle, "lights[" + std::to_string(i) + "].Position");
    glUniform3f(pos_loc, lightPositions[i].x, lightPositions[i].y, lightPositions[i].z);

But I got an error message regarding glGetUniformLocation() because of the parameter-list-definition of the function itself when I try this? Help is very much appreciated!

That is almost certainly what those functions are doing under the hood.

That’s because you’re passing a std::string, but OpenGL (being C, not C++) wants a char*. Use the .c_str() method.

1 Like