Search Unity

Assign Text Colour Value

Discussion in '2D' started by IcyBot, Aug 22, 2017.

  1. IcyBot

    IcyBot

    Joined:
    May 4, 2017
    Posts:
    5
    Hi

    I am using Random. Range on few pieces of text, is there a something I can use to assign each word with a hidden colour value.

    The text itself changes through a random colours but I would like to give word below a specific colour value which I can then use to relate it to a sprite.
    Code (CSharp):
    1.  
    2.     public Text colourText;
    3.  
    4.     public string[] names = new string[] { "Red", "Yellow", "Blue", "Green" };
    5.  
    6.     public string GetRandomName ()
    7.  
    8.     {
    9.         return names[Random.Range(0, names.Length)];
    10.     }
    11.  
    12.     void Start()
    13.     {
    14.         colourText.text = (GetRandomName());
    15.         colourText.color = new Color(Random.Range(0f, 1f),Random.Range(0f, 1f),Random.Range(0f, 1f),1);
    16.     }
    17. }
     
    Last edited: Aug 22, 2017
  2. PGJ

    PGJ

    Joined:
    Jan 21, 2014
    Posts:
    899
    You could create a class for your color information. Try this:

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.UI;
    5.  
    6. public class ColorInfo
    7. {
    8.     public Color color;
    9.     public string colorName;
    10. }
    11.  
    12. public class Test : MonoBehaviour
    13. {
    14.     public ColorInfo[] colorInfo =
    15.         new ColorInfo[] {
    16.             new ColorInfo {
    17.                 color = new Color(1,1,1),
    18.                 colorName = "White"
    19.             },
    20.             new ColorInfo {
    21.                 color = new Color(.5f,.5f,.5f),
    22.                 colorName = "Gray"
    23.             }
    24.         };
    25.  
    26.     public Text colourText;
    27.  
    28.     void Start()
    29.     {
    30.         ColorInfo colorInfo = GetRandomColorInfo();
    31.  
    32.         colourText.text = colorInfo.colorName;
    33.         colourText.color = colorInfo.color;
    34.     }
    35.  
    36.     public ColorInfo GetRandomColorInfo()
    37.     {
    38.         return colorInfo[Random.Range(0, colorInfo.Length)];
    39.     }
    40. }
    41.  
     
    IcyBot likes this.