Is there anyway to only show a part of a GUI image during the game? (C#)

I used to make games using XNA, and one of the cool things about it was that for healthbars, you didn’t need to create tonnes of images for each value of health.

Instead, you just have one image, and you can make it so that you can only show part of an image, and make it get smaller or bigger in game by using a Rect in the draw script, you do this by on the draw function, you can put in a rectangle, and it will only show what is in the rectangle

For example, a health bar, you can make it as a big or small as you like, depending on the health, the rect that the game has to show is the same height as the health bar, but the width is the changes depending on the health, the lower your health, the smaller the bar.

Is there anyway to do this with Unity?

I want to use a GUITexture for it, because the healthbar I’ve made had a gradient going from red to green, and the end of it is slanted, so a box wouldn’t be the best thing to use, I don’t want to scale it either, because I think that would ruin it.

UPDATE: Here’s my code:

		health = (masterScript.health / masterScript.maxHealth);
		GUI.DrawTextureWithTexCoords(new Rect(gameObject.transform.position.x, 
			gameObject.transform.position.y, 1,1)
			, texture, new Rect(0,0, 1, health), false);

I’m getting a “Null Reference Exception” error for the “GUI.DrawTextureWithTexCoords” line, what am I doing wrong?

If you google this method you’ll see a lot of people complaining. The ‘texture coordinates’ are normalized float values that range around ~ 0 - 1.0f and they represent percents of the sprite image horizontally and vertically I think. Google for more. It does work like you want though.