Search Unity

Need help on changing Alpha depending on character's life

Discussion in '2D' started by sooart0504, Oct 21, 2016.

  1. sooart0504

    sooart0504

    Joined:
    Oct 21, 2016
    Posts:
    3
    Hi, It's my first time learning Unity. I've been following a youtube channel tutorials so far, and I wanted to do something specific that is not included in the video.

    I want to decrease my character's Alpha(transparency) depending on how much life my character has left.
    ex) Full = 100%, one life left= 50%, no life left=2%, etc.
    I have googled this for hours but I can't figure out which commands to use...

    1. I'm not sure whether I should make a new script, or add onto an existing script that I already wrote in order to add multiple lives to my character.

    2. I have no idea which code to use. :(

    This is the youtube tutorial I've followed (I skipped some episodes as I didn't feel the need to include enemy health, projectiles, etc.):


     
  2. sooart0504

    sooart0504

    Joined:
    Oct 21, 2016
    Posts:
    3
    If anyone needs to see my codes, I can attach some.
    Just let me know which one!
     
  3. EternalForge

    EternalForge

    Joined:
    Sep 14, 2012
    Posts:
    27
    You character is a 2D Sprite I assume, and you are programming in C#?

    SpriteRenderer renderer = GetComponent<SpriteRenderer>();
    renderer.color = new Color(0.5f, 0.5f, 0.5f, 1f); // This is RGBA (So the A is your alpha, or Opacity)
     
  4. piggybank1974

    piggybank1974

    Joined:
    Dec 15, 2015
    Posts:
    621
    If I remember in the above example don't change the first three parameters of.0.5 should be 1, as this will change the colour was well you could use a math.min (30, value) this will allow for you to see the character just a bit if it dips below 30 health assuming your using 100 as full health that is, or if you go too low you will not see the character at all.
     
  5. piggybank1974

    piggybank1974

    Joined:
    Dec 15, 2015
    Posts:
    621
    You have picked a good tutorial, I bought a while back his udemy version, his code is a bit sharp but it gets the job done.
     
  6. sooart0504

    sooart0504

    Joined:
    Oct 21, 2016
    Posts:
    3
    Yes, I am using 2d sprite for my character in c#.
    So, which script would I put this in? I have a script for managing my life count and I tried putting the code inside the update {} and it didn't work..
    Or..do I make a new script and just put this code alone?
    would I need to define anything using "public void " or something like that?
     
  7. piggybank1974

    piggybank1974

    Joined:
    Dec 15, 2015
    Posts:
    621
    You count down script needs change the players colour alpha