[Unity] The use of C# function reference parameters

The reference parameter is used in the hope that after the function is executed, the value of the variable passed in has also changed.

Excerpted from: https://www.cnblogs.com/dyf96966/p/5483411.html

  1. Value parameters: When using parameters, a value is passed to a variable used by the function. Any modifications to this variable in the function will not affect the parameters specified in the function call. (Since the function has only one return value, multiple variable values ​​cannot be used as parameters).

  Second, the reference parameter: that is, the variable handled by the function is the same as the variable used in the function call, not just the variable with the same value. Therefore, any changes to this variable will affect the value of the variable used as a parameter. Parameters need to be specified with the ref keyword. Variables used as ref parameters have two limitations. Since the function may change the value of the reference parameter, "non-const" variables must be used in function calls. Second, initialized variables must be used.

  3. Output parameter: out keyword, specifies that the given parameter is an output parameter. The Out keyword is used in the same way as the ref keyword, and in fact, it executes exactly the same way as a reference parameter, because after the function is executed, the value of the parameter is returned to the variable used in the function call.

Here is the code I wrote in practice:

Call the ShowPanel function twice, bookPanelShow and historicalPanelShow are global variables.

ShowPanel(bookPanel,ref bookPanelShow);ShowPanel(historicalPanel, ref historicalPanelShow);
   void ShowPanel(CanvasGroup canvas, ref bool show)//After the function is executed, the value of the global variable also changes
    {
        if (show)
        {
            canvas.alpha = Mathf.Lerp(canvas.alpha, 1f, Time.deltaTime * 5);
            if (canvas.alpha > 0.99f)
                show = false;
        }           
    }

Use reference parameters: 1. When calling a function, add ref before the parameter 2. When declaring a function, add ref before the parameter

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325721793&siteId=291194637