C# Unity Coroutine

    IEnumerator Die()
    {
        Debug.Log("you died!");

        yield return new WaitForSeconds(1f);

        Destroy(gameObject);
    }
    private void Update()
    {
        if(Input.GetMouseButtonDown(0))
        {
            StartCoroutine("Die");
            StartCoroutine(Die());
        }
    }

Zapisywanie Coroutine w zmiennej

    IEnumerator myCoroutine;

    private void Start()
    {
        myCoroutine = Die();
    }
    
    private void Update()
    {
        if(Input.GetMouseButtonDown(0))
        {
            StartCoroutine(myCoroutine);
        }
    }

    IEnumerator Die()
    {
        Debug.Log("you died!");

        yield return new WaitForSeconds(1f);

        Destroy(gameObject);
    }

Przykład Coroutine do zmiany krycia Sprite’a

StartCoroutine / StopCoroutine

    IEnumerator myCoroutine;

    private void Start()
    {
        myCoroutine = Fade();
    }

    private void Update()
    {
        if(Input.GetMouseButtonDown(0))
        {
            StartCoroutine(myCoroutine);
        }

        if (Input.GetMouseButtonDown(1))
        {
            StopCoroutine(myCoroutine);
        }
    }

    IEnumerator Fade()
    {
        SpriteRenderer spriteRenderer = GetComponent<SpriteRenderer>();

        Color32 color = Color.white;

        for (int i = 255; i >= 0; i--)
        {
            yield return new WaitForSeconds(0.02f);
            spriteRenderer.color = new Color32(color.r, color.g, color.b, (byte)i);
        }

    }
Scroll to Top