             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

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

        return

    # @nodoc
    debug_break_on_any_gl_error: ->
        gl = @gl
        for k,v of gl when typeof v == 'function' and k != 'getError'
            gl['_'+k] = gl[k]
            gl[k] = do (k, gl) => (args...)->
                r = gl["_"+k](args...)
                if error = gl.getError()
                    debugger
                return r
        return


    # @nodoc
    # This method allows to compare performance between few objects
    # and many object with similar total poly count.
    polycount_debug: (ratio=1)->
