Unity、C#笔记 使用杂项

6 篇文章 0 订阅

预处理

#define DEBUG // 这个要声明在using关键字之前

using System;

#if DEBUG

#elif DEBUG_IOS

#else

#endif

继承MonoBehaviour
继承MonoBehaviour的类不能使用new创建,同时也不能使用构造函数。

String

// 从第0个字节找空格的位置
int n = str1.IndexOf( ' ', 0 );
// 删除第一空格后所有字符
str2 = str1.Remove(n);
// 替换所有空格为'-'
str2 = str1.Replace( ' ', '-' );
// 在空格后插入
str2 = str1.Insert( n, "test" );
// 取空格后6字符
str2 = str1.Substring( n+1, 6 );
// 已空格为标识符,分解为strs.Length个新字符串
char[] chars = { ' ' };
string[] strs = str1.Split(chars);

使用bytes

int data1 = 100;
float data2 = 0.1f;

// 转换成byte
int index = 0;
byte[] bytes = new bytes[256];
byte[] b = BitConverter.GetBytes(data1);
b.CopyTo( bytes, index );
index += 4;
b = BitConverter.GetBytes(data2);
b.CopyTo( bytes, index );

// 转换回
int readdata1 = BitConverter.ToInt32( bytes, 0 );
float readdata2 = BitConverter.ToSingle( bytes, 4 );

Awake and Start
Awake 即使不是script不enable也会调用
Start在enable时调用

Value and Reference
Vector3 和 Quaternion是Structs是Value
Transform和GameObject是Classes是Reference

Invoke
Invoke( “functionName”, 3 ); 3秒后调用functionName().
被触发的函数必须是void且没有参数
InvokeRepeating( “functionName”, 3, 1 );3秒后开始,每隔1秒周期调用
CancelInvoke( “functionName” );

Enumeration
改变enum的类型为short
enum Direction : short { North,East,South, West };

Generic

public T GenericMethod<T>( T param ) where T : class

where后面:
class可以指明是个refence type
struct可以指明是个value type
new()可以指明没有参数的构造
MonoBehaviour可以指明是这个类或它的子类
IEnumerbale可以指明实现了借口的

Extension method
static method 在一个 static class里,第一个参数this 代表编辑的instance

例如,扩展一个enum
public enum Direction {
	North, East, South, West
}
public static class DirectionExtensions {
	static Quaternion[] rotations = {
		Quaternion.identity,
		Quaternion.Euler(0f, 90f, 0f),
		Quaternion.Euler(0f, 180f, 0f),
		Quaternion.Euler(0f, 270f, 0f)
	};

	public static Quaternion GetRotation (this Direction direction) {
		return rotations[(int)direction];
	}
	}

//使用
transform.localRotation = tileFrom.PathDirection.GetRotation();

inspector 编辑属性后检查值是否有效

void OnValidate () {
		if (boardSize.x < 2) {
			boardSize.x = 2;
		}
		if (boardSize.y < 2) {
			boardSize.y = 2;
		}
	}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

好热哦

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

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

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

打赏作者

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

抵扣说明:

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

余额充值