Search Unity

Could I Optimalize this script?

Discussion in 'Scripting' started by Nexgea, Apr 25, 2015.

  1. Nexgea

    Nexgea

    Joined:
    Nov 17, 2013
    Posts:
    43
    Hi I am Object Pooling astereroids, but when they suddenly pop up it looks bad. So I have tryied to fade it with lerping transperency, which works but its taking a lot of performance.

    Calling a function
    Code (CSharp):
    1.  
    2. void OnTriggerEnter(Collider other) {
    3.         other.transform.position = GeneratedPosition();// other are Asteriods, Reposition asteriods
    4.         other.GetComponent<Fade>().Reposition ();//Calling a a component which has every asteriod
    5.        
    6.  
    7.     }
    Fade Script
    Code (CSharp):
    1.  public void Reposition () {
    2.         fade = true;
    3.         valToBeLerped = 0;
    4.         tParam = 0;
    5.     }
    6.    
    7.     // Update is called once per frame
    8.     void Update () {
    9.         if(fade){
    10.             if (tParam < 1) {
    11.                 tParam += Time.deltaTime * speed; //This will increment tParam based on Time.deltaTime multiplied by a speed multiplier
    12.                 valToBeLerped = Mathf.Lerp(0, 1, tParam);
    13.                 Rend = GetComponent<Renderer>();
    14.                 color.a =valToBeLerped;
    15.                 Rend.material.color =color;
    16.  
    17.             }
    18.     }
    19. }
    Is there way to optimaze it or do it better?
    Thanks
     
  2. Fluzing

    Fluzing

    Joined:
    Apr 5, 2013
    Posts:
    815
    It might be better to use animations to do this. Just start at color.a = 0 and set it to 1 after a certain interval. Also, GetComponent is expensive. You should not do that in Update. If you want to keep doing it in code, use a coroutine and create a reference to the Renderer.
     
  3. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
    Optimisation tips
    • Use coroutines instead of Update
    • Call GetComponent once
    • Keep variables in small scopes
    Here it is in practice:

    Code (CSharp):
    1.  public void Reposition () {
    2.         StartCoroutine(Fade());
    3. }
    4.    
    5. IEnumerator Update () {
    6.     Renderer renderer = GetComponent<Renderer>();
    7.     Color color = renderer.material.color;
    8.     float fadeTime = 0;
    9.     while (fadeTime < 1) {
    10.         fadeTime += Time.deltaTime * speed;
    11.         color.a = Mathf.Lerp(0, 1, fadeTime);
    12.         renderer.material.color = color;
    13.         yield return null;
    14.     }
    15. }
    Note that the OnTriggerEnter method belongs on the asteroid, not the player.
     
    Dantus likes this.
  4. Nexgea

    Nexgea

    Joined:
    Nov 17, 2013
    Posts:
    43
    It took some time to get it working(due to my silly mistake) but it works like magic! Thanks