Game Development Reference
In-Depth Information
There is also a variant of the
DrawTexture
function called
DrawTextureWithTexCoords
. This allows you to not only pick where you want the
texture drawn on to the screen, but also from which part of the source texture you
want to draw, for example:
public Texture2D myTexture;
void Start() {
myTexture = new Texture2D(125, 15);
}
void OnGUI() {
GUI.DrawTextureWithTexCoords (new Rect(325, 15, 100, 15),
myTexture ,
new Rect(10, 10, 50, 5));
}
This will pick a region from the source texture (
myTexture
) 50 pixels wide by
5 pixels high starting from position
10, 10
on the texture. It will then draw this to
the
Rect
region specified.
However, the
DrawTextureWithTexCoords
function cannot perform
scaling, it can only perform alpha blending! It will simply draw to it
the selected texture region to the size specified in the initial Rect.
DrawTextureWithTexCoords
has also been used to draw individual
sprites using the legacy GUI, which has a notion of what a sprite is.
The Button control
Unity also provides a
Button
control, which comes in two variants. The basic
Button
control which only supports a single click, whereas
RepeatButton
supports
holding down the button.
They are both instantiated the same way by using an
if
statement to capture
when the button is clicked, as shown in the following script:
void OnGUI() {
if (GUI.Button(new Rect(25, 40, 120, 30), "Button"))
{
//The button has clicked, holding does nothing
}
if (GUI.RepeatButton(new Rect(170, 40, 170, 30),
"RepeatButton"))
{
//The button has been clicked or is held down
}
}