Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Voting for the Unity Awards are OPEN! We’re looking to celebrate creators across games, industry, film, and many more categories. Cast your vote now for all categories
    Dismiss Notice
  3. Dismiss Notice

String to hex, hex to rgba?

Discussion in 'Scripting' started by DreamingInsanity, Jan 25, 2018.

  1. DreamingInsanity

    DreamingInsanity

    Joined:
    Nov 5, 2017
    Posts:
    101
    I have a (hopefully) simple question. In my script I have the hours, minutes, and secods displayed like this:
    #145723 Currently this is just a multiple varialbes stringed together. I want to be able to convert the string, this is: hours + zerogap1 + minutes + zerogap2 + seconds the zerogap making it not '2' but '02' if the seconds/minutes are under 10, to a real hex value and then that hex value to an RGBA value. This RGBA value is going to set a materials color.

    To make that easier to understand, I am recreating the Hex Clock in Unity: http://www.jacopocolo.com/hexclock/

    EDIT: is this possible in C#?

    Thanks,
    Dream
     
  2. karl_jones

    karl_jones

    Unity Technologies

    Joined:
    May 5, 2015
    Posts:
    7,822
    Last edited: Jan 25, 2018
  3. TaleOf4Gamers

    TaleOf4Gamers

    Joined:
    Nov 15, 2013
    Posts:
    825
  4. LiterallyJeff

    LiterallyJeff

    Joined:
    Jan 21, 2015
    Posts:
    2,802
    A quick look at that website's source code shows:
    Code (JavaScript):
    1. function refreshData()
    2. {
    3.     x = 1;  // x = seconds
    4.      var d = new Date()
    5.      var h = d.getHours();
    6.      var m = d.getMinutes();
    7.      var s = d.getSeconds();
    8.    
    9.      if (h<=9) {h = '0'+h};
    10.      if (m<=9) {m = '0'+m};
    11.     if (s<=9) {s = '0'+s};
    12.  
    13.      var    color = '#'+h+m+s;
    14.    
    15.     $("div.background").css("background-color", color );
    16.     $("p#hex").text(color);
    17.    
    18.     setTimeout(refreshData, x*1000);
    19. }
    This can be simplified using the DateTime class, and a string format parameter:
    Code (CSharp):
    1. string color = "#" + DateTime.Now.ToString("HHmmss");
    2. Debug.Log(color);
    3. Color c;
    4. ColorUtility.TryParseHtmlString(color, out c);
    5. Camera.main.backgroundColor = c; // use the color
     
    Last edited: Jan 25, 2018
    karl_jones and TaleOf4Gamers like this.
  5. DreamingInsanity

    DreamingInsanity

    Joined:
    Nov 5, 2017
    Posts:
    101
    Thanks for the code!

    It works perfectly! Thanks!

    Dream.
     
    karl_jones likes this.
  6. DreamingInsanity

    DreamingInsanity

    Joined:
    Nov 5, 2017
    Posts:
    101
    That works really well. Thanks!
    Dream.