[Getting Started with Unity] 19. Call Invoke regularly

[Getting Started with Unity] Calling Invoke regularly

    Hello everyone, I am Lampard~~

    Welcome to the Unity Getting Started series of blogs. The knowledge I have learned comes from Teacher Afa at Station B~Thanks 

(1) Timer

(1) Invoke word call

    We are no strangers to timers, and the schedule class on cocos is similar. In Unity, we provide us with Invoke related classes to realize the timer function

    First of all, we are familiar with the single delay call method Invoke

Unity's Invoke() method is a way to delay the execution of a method. The Invoke() method can execute the specified method after the specified time (in seconds)

The syntax of the Invoke() method is as follows:

```

Invoke(string methodName, float time);

```

where `methodName` is the name of the method to execute and `time` is the time in seconds to delay

    Ok, let's try to use this method in mainLogic next. We printed the current time in the start method, and Invoke called the TryInvoke method, and the time when it was called was printed in TryInvoke

    The code is very simple. It should be noted that the function name passed in to Invoke is a string, and an error will be reported every time double quotation marks are added.

    void Start()
    {
        Debug.Log("当前的时间是" + Time.time);
        this.Invoke("TryInvoke", 2);
    }

    void TryInvoke()
    {
        Debug.Log("执行方法的时间是" + Time.time);
    }

    Look at the result, it is indeed called after 2 seconds, no problem. And the tryInvoke method is only executed once

(2) InvokeRepeating repeated calls

    Then I want to repeat the call? Want to execute it every two seconds.

    Yes, then you need to use the InvokeRepeating method

InvokeRepeating() is a timer method provided by Unity, which is used to repeatedly execute the specified method at the specified time interval (in seconds). The syntax of the InvokeRepeating() method is as follows:

```

InvokeRepeating(string methodName, float time, float repeatRate);

```

where `methodName` is the name of the method to execute, `time` is the time to delay (in seconds), and `repeatRate` is the time interval (in seconds) to repeat

   It can be seen that compared with Invoke, this method only has one more parameter for repeated execution time . For example, if I want to execute it every two seconds, the code can be written like this:

    void Start()
    {
        Debug.Log("当前的时间是" + Time.time);
        this.InvokeRepeating("TryInvoke", 2, 2);
    }

    void TryInvoke()
    {
        Debug.Log("执行方法的时间是" + Time.time);
    }

    Look at the effect, it will be executed repeatedly: 

(3) Whether IsInvoking is calling

    For example, now it is executed every 2 seconds. I suddenly want to stop the timer. For example, if the player clicks the left mouse button, what should I write to stop the timer?

    First of all, we need to determine whether the following method is in the timer call, this method is IsInvokeing

IsInvoking is a method provided by Unity to determine whether a method is being called by the Invoke or InvokeRepeating method . The syntax of the IsInvoking method is as follows:

```

bool IsInvoking(string methodName);

```

Among them, `methodName` is the name of the method to be judged

    So we can write a method to monitor mouse clicks in the update method, and then determine whether this method is called by a timer when the mouse is clicked

    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            if (this.IsInvoking("TryInvoke"))
            { 
                // 取消调用
            }
        }
    }

(4) CancelInvoke to cancel the call

    The next step is to cancel the timer call. Unity also provides us with a method, CancelInvoke

CancelInvoke is a method provided by Unity to cancel the Invoke or InvokeRepeating method call of a method . The syntax of the CancelInvoke method is as follows:

```

void CancelInvoke();

void CancelInvoke(string methodName);

```

Among them, the first overload has no parameters and can cancel all methods being called by the Invoke or InvokeRepeating method; the second overload needs to pass in the name of the method to be canceled, and can only cancel the specified method call

   It can be seen that we can pause the timer by passing parameters or not passing parameters. If we do not pass parameters, all timers will be stopped . This method is a bit violent, so we are more precise, and try the second method

    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            if (this.IsInvoking("TryInvoke"))
            {
                Debug.Log("取消计时器");
                this.CancelInvoke("TryInvoke");
            }
        }
    }

    Look at the final effect, so far we are familiar with the four timers commonly used by unity:

(2) Demo fan

    After learning a new method, how can we play it without writing a demo?

    Next, we prepared an electric fan model, through the method of Inovke to achieve the effect of acceleration and deceleration , first import this fan model into the project

    Next, let's assign the Earth's RotateLogic script to him, and let it rotate for a look

     As you can see, it is spinning happily. But it looks weird, first of all, the fan is too slow , and secondly, the speed should be accelerated slowly, not so fast as soon as it runs

    Then let's continue to add logic:

    void Start()
    {
        this.speed = 0;
    }

    void Update()
    {
        this.transform.Rotate(0, this.speed * Time.deltaTime, 0);
        if (Input.GetMouseButtonDown(0))
        {
            this.InvokeRepeating("ChangeSpeed", 0, 1);
        }
    }

    void ChangeSpeed()
    {
        if (this.speed < 500) 
        {
            this.speed += 50;
        }
    }

    First, the default speed is 0. After clicking, execute the ChangeSpeed ​​method repeatedly without intervals, modify the value of the speed, and finally see the effect:

Alright, that's all for today, thank you all for reading! ! !
Like and follow! ! !

Guess you like

Origin blog.csdn.net/cooclc/article/details/130396800