C# Extension trong Unity: Delay Action Coroutine

Việc chờ một khoảng thời gian rồi gọi một (hoặc nhiều) hàm trong một project thì cách đơn giản nhất là sử dụng Coroutine. Cách thông thường nhất là viết hàm thực thi Coroutine trong class MonoBehaviour.

Ở đây mình sẽ gọi hàm EndAction() sau một khoảng thời gian là 5s từ khi bắt đầu gọi hàm StartAction().

 private void StartAction()
    {
        float waitTime = 5f;
        StartCoroutine(CoroutineDelayAction(waitTime));
    }

    private void EndAction()
    {
        Debug.Log("End Action");
    }

    private IEnumerator CoroutineDelayAction(float waitTime)
    {
        yield return new WaitForSeconds(waitTime);
        EndAction();
    }

Như vậy nếu mỗi lần muốn sử dụng chức năng này thì mỗi class MonoBehaviour đều phải viết lại (hoặc copy and paste) thì sẽ khá cồng kềnh và tốn thời gian. Vậy còn cách nào đơn giản hơn không? Đó chính là sử dụng Extension methods. Vậy Extension methods là gì?

Extension methods enable you to add methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. C# extension methods a special kind of static method that is called as if it was an instance methods on the extended type

https://www.c-sharpcorner.com

Vậy để đơn giản hoá vấn đề và tiết kiệm thời gian, chúng ta sẽ tạo một class static rồi viết hàm thực thi Coroutine vào trong đó.

public static class Extension
{
    public static void StartDelayAction(this MonoBehaviour mono, float waitTime, Action callback)
    {
        mono.StartCoroutine(CoroutineDelay(callback, waitTime));
    }

    private static IEnumerator CoroutineDelay(Action callback, float waitTime)
    {
        yield return new WaitForSeconds(waitTime);
        callback.Invoke();
    }
}

Như vậy là khi ở một class MonoBehaviour muốn sử dụng tính năng này chỉ cần gọi vào hàm StartDelayAction của class Extension.

  private void StartAction()
    {
        float waitTime = 5f;
        Debug.Log("Start");

        //gọi hàm Delay trong Extension 
        this.StartDelayAction(waitTime, () =>
        {
            EndAction();
        });
    }

    private void EndAction()
    {
        Debug.Log("End");
    }

Theo dõi
Thông báo của
guest
2 Comments
Cũ nhất
Mới nhất Được bỏ phiếu nhiều nhất
Phản hồi nội tuyến
Xem tất cả bình luận

Hãy để Gini Webseo tư vấn cho bạn

    All in one