当前位置:网站首页>Unity3D中的ref、out、Params三种参数的使用
Unity3D中的ref、out、Params三种参数的使用
2022-08-05 05:18:00 【IT学徒.】
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()
{
}
}
输出:
边栏推荐
猜你喜欢
随机推荐
栈区中越界可能造成的死循环可能
硬核!Cocos开发面试必备十问,让你offer拿到手软
【UiPath2022+C#】UiPath 数据操作
网络信息安全运营方法论 (中)
“元宇宙”是个啥?都有哪些大招?
【nodejs】第一章:nodejs架构
什么是全栈设计师?
C语言—三子棋的实现
Redis设计与实现(第二部分):单机数据库的实现
WCH系列芯片CoreMark跑分
1004 成绩排名 (20 分)
【ts】typescript高阶:联合类型与交叉类型
【ts】typescript高阶:键值类型及type与interface区别
偷题——腾讯游戏开发面试问题及解答
《基于机器视觉测量系统的工业在线检测研究》论文笔记
C语言查看大小端(纯代码)
【shell编程】第三章:函数
深度学习系列(二)优化器 (Optimization)
二、自动配置之底层注解
【ts】typeScript高阶:any和unknown









