[SOLVED] GUI.DrawTexture: inconsistency with flipped rect

I just tried to flip a texture by passing a negative rectangle width to GUI.DrawTexture(). This works, but if it gets called again with a positive rectangle width, the texture remains flipped.

This occurred in the following code, which displays a flipped image for my player (avatar) depending on if the player is walking left or right.

	public void OnGUI()
	{
		Vector3 playerScreenPos = Camera.main.WorldToScreenPoint (transform.position);
		playerScreenPos.y = Screen.height - playerScreenPos.y;
		const float PLAYER_WIDTH_PX = 64.0f;
		const float PLAYER_HEIGHT_PX = 128.0f;
		if (lookDirection == Direction.LEFT)
		{
			Debug.Log("looking left");
			GUI.DrawTexture(new Rect(playerScreenPos.x + (PLAYER_WIDTH_PX/2.0f), playerScreenPos.y - (PLAYER_HEIGHT_PX/2.0f), -PLAYER_WIDTH_PX, PLAYER_HEIGHT_PX * 0.5f), texture);
		}
		else
		{
			Debug.Log("looking right");
			GUI.DrawTexture(new Rect(playerScreenPos.x - (PLAYER_WIDTH_PX/2.0f), playerScreenPos.y - (PLAYER_HEIGHT_PX/2.0f), PLAYER_WIDTH_PX, PLAYER_HEIGHT_PX), texture);
		}
	}

So if the code looks like this, the player is always drawn flipped.

If I disable the first call to GUI.DrawTexture, the player is drawn non-flipped when walking right. Nothing is drawn when walking left.

Am I missing something or should I file a bug report?

I think this is actually a strange bug with the C# compiler. It attempts to optimise cases where constants are declared and then only used with a negative sign in front by storing the negated constant value. However, it does this even when the constant is used without negation elsewhere. Try removing the const declaration (ie, declare the values as variables) and see if this improves matters.

(Incidentally, I reported this bug to Mono some time ago and it was fixed - it’s just that the C# compiler supplied with Unity hasn’t been updated since then.)

I already used a workaround, but when I saw your reaction I tried the same code again, and it worked.

I guess this compiler bug only occurs in some circumstances.