Unity3D中的ref、out、Params三种参数的使用

目录

ref

作用:
将一个变量传入一个函数中进行"处理","处理"完成后,再将"处理"后的值带出函数。
语法:
使用时形参和实参都要添加ref关键字。

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

public class Test: MonoBehaviour {
	void Start () {
        int a = 1;
        int b = 2;
        refTest(ref a, b);
        Debug.Log("a:" + a + " " + "b:" + b);
	}
    private void refTest(ref int num1,int num2)
    {
        num1 = 5;
        num2 = 10;

    }
	void Update () {
		
	}
}

输出:
在这里插入图片描述

out

作用:
一个函数中如果返回多个不同类型的值,就需要用到out参数。
语法:
函数外部可以不为变量赋值,但是函数内部必须为函数赋值。且形参和实参都要添加out关键字。

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

public class Test : MonoBehaviour
{
    void Start()
    {
        int b;
        outTest(out b);
        Debug.Log("b:" + b);
    }
    private void outTest(out int num1)
    {
        num1 = 5;

    }
    void Update()
    {
        
    }
}

输出:
在这里插入图片描述
注意:
out修饰的参数真正赋值是在函数内部,在外部赋值没有用处,具体如下:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Test : MonoBehaviour
{
    void Start()
    {
        int b;
        b = 10;
        outTest(out b);
        Debug.Log("b:" + b);
    }
    private void outTest(out int num1)
    {
        num1 = 5;

    }
    void Update()
    {
        
    }
}

输出
在这里插入图片描述

Params

可变参数params(数组参数)允许我们动态传入不同个数的参数。

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

public class Test : MonoBehaviour
{
    public void Getdd(params int[] pp)
    {
        foreach (var p in pp)
        {
            print(p);
        }
    }
    void Start()
    {
        Getdd(1, 2, 3);
    }
    void Update()
    {
    }
}

输出:
在这里插入图片描述

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

IT学徒.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值