Unity的C#编程教程_48_有返回值的函数/方法

3. Return Type Functions

  • 如何获取方法中的数据,或者如何让方法返回一些运算结果呢?
  • 那就不能用 void 类型的方法了,因为这个是没有返回值的方法
  • 如果我们要获得一个返回值,那这里的 void 就替换成返回值的类型

比如一个加法方法:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Test2 : MonoBehaviour
{

    public int result; // 用于存储加法运算后的结果

    // Start is called before the first frame update
    void Start()
    {
        result = Sum(4, 3); // 调用方法计算,并获取返回值
        Debug.Log(result);
    }

    // Update is called once per frame
    void Update()
    {
        
    }

    private int Sum(int a,int b)
    {
        return a + b; // 返回一个计算结果
    }
}

这里如果我们不用 return,而是直接在方法中写上 result = a+b 结果也是一样的,但是这个方法就只能用在这里,而不能进行复用,比如我另一个地方也要计算加法,那这个加法运算的方法就不能用了呀,所以一定要用有返回值的这种方法。

Tags: