预处理
#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;
}
}