Game Development Reference
In-Depth Information
Listing 5-7. Creating Textures
039 //Called when object is created
040 void Start()
041 {
042 //Get First person capsule and make non-visible
043 MeshRenderer Capsule = GetComponentInChildren<MeshRenderer>();
044 Capsule.enabled = false;
045
046 //Get Animator
047 AnimComp = GetComponentInChildren<Animator>();
048
049 //Create damage texture
050 DamageTexture = new Texture2D(1,1);
051 DamageTexture.SetPixel(0,0,new Color(255,0,0,0.5f));
052 DamageTexture.Apply();
053
054 //Get cached transform
055 ThisTransform = transform;
056 }
The Start event for PlayerController has been amended to create a texture in code to be used as
a red damage texture when damage is taken. This red texture could have been created manually in
an image editor and imported as a texture asset; but when bold-color textures are required (often
red, black, and white) it's usually more convenient to generate them from code. Here, a texture of
size 1×1 pixel in dimensions is created, and the SetPixel method of Texture2D is used to fill the
texture with the RGB value for red. Notice that the Apply method has also been called to confirm
the SetPixel operation. This code doesn't actually display the texture on-screen; texture display is
covered in the next section. More information on Texture2D can be found in the Unity documentation
at http://docs.unity3d.com/Documentation/ScriptReference/Texture2D.html .
Note Although the red texture is generated at 1×1 pixels, it doesn't have to display on-screen at that size;
textures can be stretched . This means a 1×1-pixel red texture can be upsized to the screen dimensions
to fill the screen with red. Normally, the upsizing of textures is to be avoided due to quality loss caused by
resampling, but this is an exceptional case. Quality loss doesn't apply to a texture filled with a single color.
GUIs
The previous section demonstrated how fill textures can be generated procedurally. This section
explores how we can show textures on-screen quickly using the native GUI functionality. The Unity
GUI classes are designed to display GUI elements in screen space. And we can use them here to fill
a red texture across the screen. This happens in the native event OnGUI (see Listing 5-8, which is an
extract of Listing 5-6).
 
 
Search WWH ::




Custom Search