In-game customization and user-made content have been taking over games for a while. A very common feature is the ability of changing one's avatar color. In this recipe, we will create a dialog box that allows the player to change the object's color sliders that modify the red, green, and blue values of the material.
If you want to use our sample scene to follow this recipe, please import the package named colorSelector
, available in the folder named 0423_03_06
.
To create a color selection dialog, follow these steps:
colorSelection
scene.ColorSelector
and open it in your editor.using UnityEngine; using System.Collections; public class ColorSelector : MonoBehaviour { public float redValue = 1.0f; public float greenValue = 1.0f; public float blueValue = 1.0f; bool selectorOn = false; private float redReset = 1.0f; private float greenReset = 1.0f; private float blueReset = 1.0f; void OnMouseUp() { selectorOn = true; } void OnGUI() { if (selectorOn) { GUI.Label(new Rect(10, 30, 90, 20), "Red: " + Mathf.RoundToInt(redValue * 255)); redValue = GUI.HorizontalSlider(new Rect(80, 30, 256, 20), redValue, 0.0f, 1.0f); GUI.Label(new Rect(10, 50, 90, 20), "Green: " + Mathf.RoundToInt(greenValue * 255)); greenValue = GUI.HorizontalSlider(new Rect(80, 50, 256, 20), greenValue, 0.0f, 1.0f); GUI.Label(new Rect(10, 70, 90, 20), "Blue: " + Mathf.RoundToInt(blueValue * 255)); blueValue = GUI.HorizontalSlider(new Rect(80, 70, 256, 20), blueValue, 0.0f, 1.0f); if (GUI.Button(new Rect(10, 110, 50, 20), "Ok")) { selectorOn = false; redReset = redValue; greenReset = greenValue; blueReset = blueValue; } if (GUI.Button(new Rect(70, 110, 80, 20), "Reset")) { redValue = redReset; greenValue = greenReset; blueValue = blueReset; } renderer.material.SetColor("_Color", new Color(redValue, greenValue, blueValue, 1)); } else { GUI.Label(new Rect(10, 10, 500, 20), "Click the spaceship to change color"); } } }
ColorSelector
script to the ship
game object (and not its parent object, spaceshipColor
).ship
game object. Again, it is important that the collider is applied to ship
, not its parent object. Adding a collider can be done by selecting the object and accessing Component | Physics | Mesh Collider.Besides assigning the sliders' values to the material color, we are keeping track of the last used color, storing its values into three variables. This is necessary in case the player wants to go back to the previous color after messing up with the sliders.
Also, we multiply those values by 255 in the text label so the player can read the RGB values in a more traditional way.
3.144.39.144