3.必备知识点-随机数和Unity自带委托相关
3.1 知识点
随机数
C#中的随机数
System中的Random类。实例化Random对象。
System.Random.Next成员方法 返回随机整数
// 左包含,右不包含
System.Random random = new System.Random();
random.Next(0, 100);
Unity中的随机数
UnityEngine中的Random类。注意:此Random(Unity)非彼Random(C#)。
UnityEngine.Random.Range方法 返回随机数
// int重载,规则是左包含,右不包含
int randomNum = Random.Range(0, 100); // 0~99之间的数
// float重载,规则是左右都包含
float randomNumF = Random.Range(1.1f, 99.9f); // 1.1~99.9f之间的数
委托
C#的自带委托
- 无参无返回的委托
System.Action ac = () =>
{
print("123");
};
- int和float作为参数无返回值的委托
System.Action<int, float> ac2 = (i, f) =>
{
};
- 无参int返回值的委托
System.Func<int> fun1 = () =>
{
return 1;
};
- int作为参数string作为返回值的委托
System.Func<int, string> fun2 = (i) =>
{
return "123";
};
Unity的自带委托
要引用using UnityEngine.Events;
命名空间。
- 无参无返回的委托
UnityAction uac = () =>
{
};
- string作为参数无返回值的委托
UnityAction<string> uac1 = (s) =>
{
};
3.2 知识点代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
public class Lesson03_必备知识点_随机数和Unity自带委托相关 : MonoBehaviour
{
void Start()
{
#region 知识点一 随机数
//C#中的随机数
//System中的Random类
//左包含 右不包含
System.Random random = new System.Random();
random.Next(0, 100);
//Unity中的随机数
//UnityEngine中的Random类 此Random(Unity)非彼Random(C#)
//int重载 规则是 左包含 右不包含
int randomNum = Random.Range(0, 100);//0~99之间的数
//float重载 规则是 左右都包含
float randomNumF = Random.Range(1.1f, 99.9f);//1.1~99.9f之间的数
#endregion
#region 知识点二 委托
//C#的自带委托
//无参无返回的委托
System.Action ac = () =>
{
print("123");
};
//int和float作为参数无返回值的委托
System.Action<int, float> ac2 = (i, f) =>
{
};
//无参int返回值的委托
System.Func<int> fun1 = () =>
{
return 1;
};
//int作为参数string作为返回值的委托
System.Func<int, string> fun2 = (i) =>
{
return "123";
};
//Unity的自带委托
//要引用using UnityEngine.Events;命名空间
//UnityAction类似于C#自带的Action
//无参无返回的委托
UnityAction uac = () =>
{
};
//string作为参数无返回值的委托
UnityAction<string> uac1 = (s) =>
{
};
#endregion
}
}
转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 785293209@qq.com