             if active_texture != bound_unit
                 @active_texture = bound_unit
                 gl.activeTexture gl.TEXTURE0 + bound_unit
-
-        # TODO: debug option to check if texture is actually bound
         return bound_unit
 
     # Unbinds a texture if it was bound
     unbind_texture: (texture) ->
         {gl, bound_textures} = @
-        old_tex = bound_textures[texture.bound_unit]
+        {bound_unit} = texture
+        old_tex = bound_textures[bound_unit]
         if old_tex == texture
-            bound_textures[texture.bound_unit] = null
-            gl.activeTexture gl.TEXTURE0 + texture.bound_unit
+            bound_textures[bound_unit] = null
+            @active_texture = bound_unit
+            gl.activeTexture gl.TEXTURE0 + bound_unit
             gl.bindTexture texture.gl_target, null
             texture.bound_unit = -1
             texture.last_used_material = null

        @background_alpha = if ba? then ba else 1
        @compiled_shaders_this_frame = 0
        @use_frustum_culling = true
        # TODO: workaround until we properly manage reused textures
        @unbind_textures_on_draw_mesh = false
        @unbind_textures_on_draw_viewport = true
        @probes = []


    # TODO: Check if a shader needs more textures than available
    bind_texture: (texture, avoid_material) ->
        {gl, bound_textures, active_texture, next_texture, max_textures} = @
        if texture.bound_unit == -1
            while avoid_material? and (nt = bound_textures[next_texture])? and\
                    nt.last_used_material == avoid_material
                next_texture = (next_texture+1) % max_textures
