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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

character fading on hit?

Discussion in 'Scripting' started by lewislepton, Apr 2, 2015.

  1. lewislepton

    lewislepton

    Joined:
    Mar 25, 2015
    Posts:
    34
    this is something im looking to do rather than a healthier, which i have.

    so instead of the character just dying when the health bar reaches a point, he fades out. now i have something for the health bar, works perfectly, by all means use it.
    but how can i use this to affect the players alpha?

    here is what i have just now. i have tried playing with it, but i run into errors. have not seen anybody else ask this. so thought i may as well be the first ;)

    Code (CSharp):
    1. public float health = 100f;
    2.     public float healthTimer;
    3.  
    4.     private SpriteRenderer healthBar;
    5.     private Vector3 healthScale;
    6.  
    7.     void Start () {
    8.         healthBar = GameObject.Find ("HealthBar").GetComponent<SpriteRenderer> ();
    9.         healthScale = healthBar.transform.localScale;
    10.     }
    11.  
    12.     void FixedUpdate () {
    13.         if(health <= 0){
    14.             Destroy(this.gameObject);
    15.         }
    16.         if(health > 100){
    17.             health = 100;
    18.         }
    19.         HealthUpdate();
    20.     }
    21.  
    22.     void HealthUpdate(){
    23.         healthBar.transform.localScale = new Vector3(healthScale.x * health * 0.01f, 1, 1);
    24.     }
    25.  
    26.     void OnCollisionEnter2D(Collision2D enemyHit){
    27.         if (enemyHit.gameObject.tag == "Enemy"){
    28.             health -= 3;
    29.         }
    30.  
    31.         if(enemyHit.gameObject.tag == "HealthPickUp"){
    32.             health += 10;
    33.         }
    34.     }
     
  2. GroZZleR

    GroZZleR

    Joined:
    Feb 1, 2015
    Posts:
    3,201
    Grab the Renderer component and change the alpha value on the material being used. Make sure you're using a transparent shader for the object.

    Something like this should set it to half transparency:
    Code (csharp):
    1.  
    2. Renderer renderer = gameObject.GetComponent<Renderer>();
    3. renderer.material.color.a = 0.5f;
    4.  
     
  3. lewislepton

    lewislepton

    Joined:
    Mar 25, 2015
    Posts:
    34
    ill give that a shot thanks. was trying until 2am, but thought that i should really get some sleep ;)