unity3d time-testing



  • The object has to change its transparency, to ten seconds, and then to return to its original state. I've come up with this.

    public SpriteRenderer _sprite; 
    

    public void Invisibility ()
    {

    var color = _sprite.color;
    color.a = 0.4f;
    _sprite.color = color;
    StartCoroutine(Timer());
    

    }
    IEnumerator Timer() {
    var color = _sprite.color;
    yield return new WaitForSeconds(10);
    color.a = 1;
    _sprite.color = color;
    }

    But I don't think it's good.



  • The approach you're using is perfectly normal and has the right to life.

    If there was a code on the page, there might be something that could be corrected.

    And this code can only be slightly edited by removing color to the declared variable so that you don't write var color = _sprite.color; and functions Timer() At the end, write StopCoroutine("Timer")

    Example:

    using UnityEngine;
    using System.Collections;
    

    public class EnumeratorTest : MonoBehaviour {

    public SpriteRenderer _sprite;
    private Color _spriteColor;
    
    void Start() {
        _sprite = GetComponent<SpriteRenderer>();
        _spriteColor = _sprite.color;
    }
    
    public void Invisibility () {        
        _spriteColor.a = 0.4f;
        _sprite.color = _spriteColor;
        StartCoroutine(Timer());
    }
    
    IEnumerator Timer() {        
        yield return new WaitForSeconds(5);
        _spriteColor.a = 1;
        _sprite.color = _spriteColor;
        StopCoroutine ("Timer");
    }
    

    }

    If further optimization is made, it is possible to make a simple, separate maaaaaaaaagne function that can be used to change the channel alpha. That's how this whole thing looks:

    using UnityEngine;
    using System.Collections;

    public class EnumeratorTest : MonoBehaviour {

    public SpriteRenderer _sprite;
    
    void Start() {
        _sprite = GetComponent<SpriteRenderer>();
    }
    
    public void Invisibility () {
        SetOpacity(_sprite, 0.4f);
        StartCoroutine(Timer());
    }
    
    IEnumerator Timer() {        
        yield return new WaitForSeconds(5);
        SetOpacity(_sprite, 1);
        StopCoroutine ("Timer");
    }
    
    
    private void SetOpacity(SpriteRenderer sprite, float opacity) {
        sprite.color = new Color(sprite.color.r, sprite.color.g, sprite.color.b, opacity);
    }
    

    }

    Well, of course, don't forget that it's best not to use magical numbers like that. 0.4fand describe them as an declared variable and put it in a function.

    And in general, your code is the code.




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2