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

Script effects all the game objects which have same component in U.I Canvas

Discussion in 'Scripting' started by felixwcf, Apr 3, 2015.

  1. felixwcf

    felixwcf

    Joined:
    May 22, 2012
    Posts:
    16
    Hi, I have written a fade-in script which is
    Code (CSharp):
    1.    
    2. Text text;
    3.  
    4. void Start () {
    5.        text = this.gameObject.GetComponent<Text> ();
    6.  }
    7.  
    8.  void Update () {
    9.  
    10.         if(Time.time > period){
    11.             fadeIsDone = true;
    12.         }
    13.  
    14.         if (!fadeIsDone) {
    15.             Text text = gameObject.GetComponent<Text>();
    16.             Color colorOfObject = text.color;
    17.             float prop = (Time.time / period);
    18.             colorOfObject.a = Mathf.Lerp(0, 0.9f, prop);
    19.             text.material.color = colorOfObject;
    20.         }
    21.        
    22.     }
    and apply it into Text object under Canvas. Weird thing happen as all of the Text objects under Canvas will receive the same fade-in effect which is caused from the script.

    Did anyone has this problem?
    I'm using Unity 4.6.

    Thank you.
     
  2. PeppyZee

    PeppyZee

    Joined:
    Apr 1, 2015
    Posts:
    20
    I am new to the UI scripting as well, however if I recall correctly you will have to make a reference to the particular text item you want to effect with the script if not all by its individual ID or Name...

    Personally I have not gotten that far, I am still learning how to interact with it via script, so my suggestion is as much as a suggestion as it is a question.. I hope we both get the answer :)

    Cheers bro, will check back to see if you have receive a informative response and if the responders would be so kind as to post some script examples..
     
  3. PGJ

    PGJ

    Joined:
    Jan 21, 2014
    Posts:
    897
    The problem is that you are assigning the color of the material, rather than the color. Change:
    Code (CSharp):
    1. text.material.color = colorOfObject;´
    2.  
    to:
    Code (CSharp):
    1. text.color = colorOfObject;
    Then things will work as intended.
     
    felixwcf likes this.
  4. felixwcf

    felixwcf

    Joined:
    May 22, 2012
    Posts:
    16
    Hi PGJ, thanks for solving my bug. It's working now.