1 Application类
2 Camera类
3 GameObject类
4 HideFlags类
5 Mathf类
6 Matrix4x4类
7 Object类
8 Quaternion类
9 Random类
10 Rigidbody类
11 Time类
12 Transform类
13 Vector2类
14 Vector3类
1 Application类
1 using UnityEngine; 2 using System.Collections; 3 4 public class DataPath_ts : MonoBehaviour 5 { 6 void Start() 7 { 8 //四种不同的path,都为只读 9 //dataPath和streamingAssetsPath的路径位置一般是相对程序的安装目录位置 10 //persistentDataPath和temporaryCachePath的路径位置一般是相对所在系统的固定位置 11 Debug.Log("dataPath:" + Application.dataPath); 12 Debug.Log("persistentDataPath:" + Application.persistentDataPath); 13 Debug.Log("streamingAssetsPath:" + Application.streamingAssetsPath); 14 Debug.Log("temporaryCachePath:" + Application.temporaryCachePath); 15 } 16 }
DataPath
1 using UnityEngine; 2 using System.Collections; 3 4 public class LoadedLevel_ts : MonoBehaviour 5 { 6 void Start() 7 { 8 //返回当前场景的索引值 9 Debug.Log("loadedLevel:" + Application.loadedLevel); 10 //返回当前场景的名字 11 Debug.Log("loadedLevelName:" + Application.loadedLevelName); 12 //是否有场景正在被加载 13 Debug.Log("isLoadingLevel:" + Application.isLoadingLevel); 14 //返回游戏中可被加载的场景数量 15 Debug.Log("levelCount:" + Application.levelCount); 16 //返回当前游戏的运行平台 17 Debug.Log("platform:" + Application.platform); 18 //当前游戏是否正在运行 19 Debug.Log("isPlaying:" + Application.isPlaying); 20 //当前游戏是否处于Unity编辑模式 21 Debug.Log("isEditor:" + Application.isEditor); 22 } 23 }
LoadedLevel
1 using UnityEngine; 2 using System.Collections; 3 4 public class CaptureScreenshot_ts : MonoBehaviour 5 { 6 int tp = -1; 7 void Update() 8 { 9 if (tp == 0) 10 { 11 //默认值,不放大 12 Application.CaptureScreenshot("test01.png", 0); 13 } 14 else if (tp == 1) 15 { 16 //放大系数为1,即不放大 17 Application.CaptureScreenshot("test02.png", 1); 18 } 19 else 20 { 21 //放大系数为2,即放大2倍 22 Application.CaptureScreenshot("test03.png", 2); 23 } 24 tp++; 25 } 26 }
CaptureScreenshot
1 using UnityEngine; 2 using System.Collections; 3 4 public class Capture_Use_ts : MonoBehaviour 5 { 6 7 //td:用来指向屏幕截图 8 Texture2D td = null; 9 //txt_bg:用来指向文本输入的背景图片 10 //可以指向一张纯色的图片,也可以自定义一个纯色的背景 11 //本程序自定义了一个纯色的背景 12 Texture2D txt_bg; 13 //txt_w和txt_h用来记录文本框的宽度和高度 14 int txt_w, txt_h; 15 //my_save_path:用来记录截图的保存路径 16 string my_save_path = ""; 17 //show_txt:用来记录输入的文本 18 string show_txt = "在此输入"; 19 //my_colors:用来记录文本输入框的纹理颜色 20 Color[] my_colors; 21 //_w和_h用来记录my_colors的宽度和高度 22 int _w, _h; 23 //step:用来记录当前状态,step共有3种状态: 24 //step=0时,是等待状态,等待在文本框中输入文本 25 //step=1时,即点击“确定”按钮后,生成截图并保存 26 //step=2时,读取截图信息 27 //step=3时,是对读取的截图信息进行有选择的提取,并生成想要展示的内容 28 int step = 0; 29 //go:用来指向拼字所用物体对象 30 public GameObject go; 31 //gos:用来记录所有的go对象 32 GameObject[] gos; 33 //gos_max用来记录gos的最大容量 34 int gos_max; 35 //gos_cur用来记录gos当前使用值 36 int gos_cur = 0; 37 //is_show:用来记录图像矩阵中某个点是否需要展示物体 38 bool[,] is_show; 39 40 void Start() 41 { 42 //初始化文本框的宽度和高度 43 txt_w = 200; 44 txt_h = 80; 45 //初始化截取区间的大小,为了避免边界识别错误,其值应该比文本框的宽度和高度少几个像素 46 _w = txt_w; 47 _h = txt_h; 48 _w -= 5; 49 _h -= 5; 50 //自定义txt_bg纹理 51 txt_bg = new Texture2D(txt_w, txt_h); 52 Color[] tdc = new Color[txt_w * txt_h]; 53 for (int i = 0; i < txt_w * txt_h; i++) 54 { 55 //所用像素点颜色应相同 56 tdc[i] = Color.white; 57 } 58 txt_bg.SetPixels(0, 0, txt_w, txt_h, tdc); 59 60 is_show = new bool[_h, _w]; 61 //初始化gos_max,其值大小为_w * _h的三分之一在一般情况下就够用了 62 gos_max = _w * _h / 3; 63 //实例化gos,使其随机分布_w和_h的区间内 64 gos = new GameObject[gos_max]; 65 for (int i = 0; i < gos_max; i++) 66 { 67 gos[i] = (GameObject)Instantiate(go, new Vector3(Random.value * _w, Random.value * _h, 10.0f), Quaternion.identity); 68 gos[i].GetComponent<Capture_Use_Sub_ts>().toward = gos[i].transform.position; 69 } 70 //存储初始界面截图 71 my_save_path = Application.persistentDataPath; 72 Application.CaptureScreenshot(my_save_path + "/ts02.png"); 73 74 } 75 76 void Update() 77 { 78 switch (step) 79 { 80 case 0: 81 break; 82 case 1: 83 step = 0; 84 //截图并保存 85 my_save_path = Application.persistentDataPath; 86 Application.CaptureScreenshot(my_save_path + "/ts02.png"); 87 //给电脑一点儿时间用来保存新截取的图片 88 Invoke("My_WaitForSeconds", 0.4f); 89 Debug.Log(my_save_path); 90 break; 91 case 2: 92 //由于在读取截图纹理的时候,一帧之内可能无法读完 93 //所以需要step=0,避免逻辑出现混乱 94 step = 0; 95 //读取截图信息 96 my_save_path = Application.persistentDataPath; 97 StartCoroutine(WaitLoad(my_save_path + "/ts02.png")); 98 break; 99 case 3: 100 //在计算并生成展示信息的时候,一帧之内可能无法完成 101 //所以需要step=0,避免逻辑出现混乱 102 step = 0; 103 //计算并生成展示信息 104 Cum(); 105 break; 106 } 107 } 108 109 //计算并生成展示信息 110 void Cum() 111 { 112 if (td != null) 113 { 114 float ft; 115 //ft:用来记录文本框左下角像素的R通道值,用来作为后面的参照 116 ft = td.GetPixel(2, td.height - _h).r; 117 //截取文本框纹理信息 118 //需要注意的是,纹理坐标系和GUI坐标系不同 119 //纹理坐标系以坐下角为原点,而GUI坐标系以左上角为原点 120 //以2为x方向起点是为了避免截图边缘的痕迹 121 my_colors = td.GetPixels(2, td.height - _h, _w, _h); 122 int l = my_colors.Length; 123 Debug.Log("length: " + l); 124 //通过遍历my_colors的R值,将其与ft比较来确定是否需要展示物体 125 for (int i = 0; i < l; i++) 126 { 127 is_show[i / _w, i % _w] = my_colors[i].r == ft ? false : true; 128 } 129 //根据is_show的值排列gos中物体的位置 130 for (int i = 0; i < _h; i++) 131 { 132 for (int j = 0; j < _w; j++) 133 { 134 if (is_show[i, j]) 135 { 136 if (gos_cur < gos_max) 137 { 138 gos[gos_cur].GetComponent<Capture_Use_Sub_ts>().toward = new Vector3(j, i, 0.0f); 139 gos[gos_cur].SetActive(true); 140 gos_cur++; 141 } 142 //当当前gos数量不够用时需要扩充gos的容量 143 else 144 { 145 Debug.Log("容量过小"); 146 int temps = gos_max; 147 //将gos容量扩大1.5倍 148 gos_max = (int)(gos_max * 1.5f); 149 GameObject[] tps = new GameObject[gos_max]; 150 for (int k = 0; k < temps; k++) 151 { 152 tps[k] = gos[k]; 153 } 154 for (int k = temps; k < gos_max; k++) 155 { 156 tps[k] = (GameObject)Instantiate(go, new Vector3(Random.value * _h, Random.value * _w, 10.0f), Quaternion.identity); 157 tps[k].GetComponent<Capture_Use_Sub_ts>().toward = tps[k].transform.position; 158 } 159 160 gos = new GameObject[gos_max]; 161 gos = tps; 162 163 gos[gos_cur].GetComponent<Capture_Use_Sub_ts>().toward = new Vector3(j, i, 0.0f); 164 gos[gos_cur].SetActive(true); 165 gos_cur++; 166 167 } 168 169 } 170 } 171 } 172 //隐藏gos中未曾用到的物体 173 for (int k = gos_cur; k < gos_max; k++) 174 { 175 gos[k].SetActive(false); 176 } 177 } 178 } 179 //绘制界面 180 void OnGUI() 181 { 182 //绘制纹理作为TextField的背景 183 GUI.DrawTexture(new Rect(0.0f, 0.0f, txt_w, txt_h), txt_bg); 184 GUIStyle gs = new GUIStyle(); 185 gs.fontSize = 50; 186 show_txt = GUI.TextField(new Rect(0.0f, 0.0f, txt_w, txt_h), show_txt, 15, gs); 187 188 if (GUI.Button(new Rect(0, 100, 80, 45), "确定")) 189 { 190 //取消在TextField中的焦点 191 GUI.FocusControl(null); 192 //重置gos_cur的值 193 gos_cur = 0; 194 step = 1; 195 } 196 //程序退出 197 if (GUI.Button(new Rect(0, 155, 80, 45), "退出")) 198 { 199 Application.Quit(); 200 } 201 } 202 203 //加载图片 204 IEnumerator WaitLoad(string fileName) 205 { 206 WWW wwwTexture = new WWW("file://" + fileName); 207 Debug.Log(wwwTexture.url); 208 yield return wwwTexture; 209 td = wwwTexture.texture; 210 step = 3; 211 } 212 //进入步骤2 213 void My_WaitForSeconds() 214 { 215 step = 2; 216 } 217 }
Capture_Use
1 using UnityEngine; 2 using System.Collections; 3 4 public class Capture_Use_Sub_ts : MonoBehaviour 5 { 6 //物体移动的目标位置 7 public Vector3 toward; 8 //物体移动时间 9 float delays; 10 void Start() 11 { 12 //获取一个随机值 13 delays = Random.Range(2.0f, 4.0f); 14 } 15 16 void Update() 17 { 18 //通过更改物体位置来达到物体运动的效果 19 transform.position = Vector3.MoveTowards(transform.position, toward, delays); 20 } 21 }
Capture_Use_Sub
1 using UnityEngine; 2 using System.Collections; 3 4 public class RegisterLogCallback_ts : MonoBehaviour 5 { 6 string output = "";//日志输出信息 7 string stack = "";//堆栈跟踪信息 8 string logType = "";//日志类型 9 int tp = 0; 10 //打印日志信息 11 void Update() 12 { 13 Debug.Log("stack:" + stack); 14 Debug.Log("logType:" + logType); 15 Debug.Log("tp:"+(tp++)); 16 Debug.Log("output:" + output); 17 } 18 void OnEnable() 19 { 20 //注册委托 21 Application.RegisterLogCallback(MyCallback); 22 } 23 void OnDisable() 24 { 25 //取消委托 26 Application.RegisterLogCallback(null); 27 } 28 //委托方法 29 //方法名字可以自定义,但方法的参数类型要符合Application.LogCallback中的参数类型 30 void MyCallback(string logString, string stackTrace, LogType type) 31 { 32 output = logString; 33 stack = stackTrace; 34 logType = type.ToString(); 35 } 36 }
RegisterLogCallback
2 Camera类
1 using UnityEngine; 2 using System.Collections; 3 4 public class Aspect_ts : MonoBehaviour 5 { 6 void Start() 7 { 8 //camera.aspect的默认值即为当前硬件的aspect值 9 Debug.Log("camera.aspect的默认值:" + camera.aspect); 10 } 11 void OnGUI() 12 { 13 if (GUI.Button(new Rect(10.0f, 10.0f, 200.0f, 45.0f), "aspect=1.0f")) 14 { 15 camera.ResetAspect(); 16 camera.aspect = 1.0f; 17 } 18 if (GUI.Button(new Rect(10.0f, 60.0f, 200.0f, 45.0f), "aspect=2.0f")) 19 { 20 camera.ResetAspect(); 21 camera.aspect = 2.0f; 22 } 23 if (GUI.Button(new Rect(10.0f, 110.0f, 200.0f, 45.0f), "aspect还原默认值")) 24 { 25 camera.ResetAspect(); 26 } 27 } 28 }
Aspect
1 using UnityEngine; 2 using System.Collections; 3 4 public class CameraToWorldMatrix_ts : MonoBehaviour 5 { 6 void Start() 7 { 8 Debug.Log("Camera旋转前位置:" + transform.position); 9 Matrix4x4 m = camera.cameraToWorldMatrix; 10 //v3的值为沿着Camera局部坐标系的-z轴方向前移5个单位的位置在世界坐标系中的位置 11 Vector3 v3 = m.MultiplyPoint(Vector3.forward * 5.0f); 12 //v4的值为沿着Camera世界坐标系的-z轴方向前移5个单位的位置在世界坐标系中的位置 13 Vector3 v4 = m.MultiplyPoint(transform.forward * 5.0f); 14 //打印v3、v4 15 Debug.Log("旋转前,v3坐标值:" + v3); 16 Debug.Log("旋转前,v4坐标值:" + v4); 17 transform.Rotate(Vector3.up * 90.0f); 18 Debug.Log("Camera旋转后位置:" + transform.position); 19 m = camera.cameraToWorldMatrix; 20 //v3的值为沿着Camera局部坐标系的-z轴方向前移5个单位的位置在世界坐标系中的位置 21 v3 = m.MultiplyPoint(Vector3.forward * 5.0f); 22 //v3的值为沿着Camera世界坐标系的-z轴方向前移5个单位的位置在世界坐标系中的位置 23 v4 = m.MultiplyPoint(transform.forward * 5.0f); 24 //打印v3、v4 25 Debug.Log("旋转后,v3坐标值:" + v3); 26 Debug.Log("旋转后,v4坐标值:" + v4); 27 } 28 }
CameraToWorldMatrix
1 using UnityEngine; 2 using System.Collections; 3 4 public class CullingMask_ts : MonoBehaviour 5 { 6 void OnGUI() 7 { 8 //默认CullingMask=-1,即渲染任何层 9 if (GUI.Button(new Rect(10.0f, 10.0f, 200.0f, 45.0f), "CullingMask=-1")) 10 { 11 camera.cullingMask = -1; 12 } 13 //不渲染任何层 14 if (GUI.Button(new Rect(10.0f, 60.0f, 200.0f, 45.0f), "CullingMask=0")) 15 { 16 camera.cullingMask = 0; 17 } 18 //仅渲染第0层 19 if (GUI.Button(new Rect(10.0f, 110.0f, 200.0f, 45.0f), "CullingMask=1<<0")) 20 { 21 camera.cullingMask = 1 << 0; 22 } 23 //仅渲染第8层 24 if (GUI.Button(new Rect(10.0f, 160.0f, 200.0f, 45.0f), "CullingMask=1<<8")) 25 { 26 camera.cullingMask = 1 << 8; 27 } 28 //渲染第8层与第0层 29 if (GUI.Button(new Rect(10.0f, 210.0f, 200.0f, 45.0f), "CullingMask=0&&8")) 30 { 31 //注:不可大意写成camera.cullingMask = 1 << 8+1;或 32 //camera.cullingMask = 1+1<<8 ;因为根据运算符优先次序其分别等价于: 33 //camera.cullingMask = 1 << (8+1)和camera.cullingMask = (1+1)<<8; 34 camera.cullingMask = (1 << 8) + 1; 35 } 36 37 } 38 }
CullingMask
1 using UnityEngine; 2 using System.Collections; 3 4 public class EventMask_ts : MonoBehaviour 5 { 6 bool is_rotate = false;//控制物体旋转 7 public Camera c;//指向场景中摄像机 8 //记录摄像机的eventMask值,可以在程序运行时在Inspector面板中修改其值的大小 9 public int eventMask_now = -1; 10 //记录当前物体的层 11 int layer_now; 12 int tp;//记录2的layer次方的值 13 int ad;//记录与运算(&)的结果 14 string str = null; 15 16 void Update() 17 { 18 //记录当前对象的层,可以在程序运行时在Inspector面板中选择不同的层 19 layer_now = gameObject.layer; 20 //求2的layer_now次方的值 21 tp = (int)Mathf.Pow(2.0f, layer_now); 22 //与运算(&) 23 ad = eventMask_now & tp; 24 c.eventMask = eventMask_now; 25 //当is_rotate为true时旋转物体 26 if (is_rotate) 27 { 28 transform.Rotate(Vector3.up * 15.0f * Time.deltaTime); 29 } 30 } 31 //当鼠标左键按下时,物体开始旋转 32 void OnMouseDown() 33 { 34 is_rotate = true; 35 } 36 //当鼠标左键抬起时,物体结束旋转 37 void OnMouseUp() 38 { 39 is_rotate = false; 40 } 41 void OnGUI() 42 { 43 GUI.Label(new Rect(10.0f, 10.0f, 300.0f, 45.0f), "当前对象的layer值为:" + layer_now + " , 2的layer次方的值为" + tp); 44 GUI.Label(new Rect(10.0f, 60.0f, 300.0f, 45.0f), "当前摄像机eventMask的值为:" + eventMask_now); 45 GUI.Label(new Rect(10.0f, 110.0f, 500.0f, 45.0f), "根据算法,当eventMask的值与" + tp + "进行与运算(&)后, 若结果为" + tp + ",则物体相应OnMousexxx方法,否则不响应!"); 46 47 if (ad == tp) 48 { 49 str = " ,所以物体会相应OnMouseXXX方法!"; 50 } 51 else 52 { 53 str = " ,所以物体不会相应OnMouseXXX方法!"; 54 } 55 GUI.Label(new Rect(10.0f, 160.0f, 500.0f, 45.0f), "而当前eventMask与" + tp + "进行与运算(&)的结果为" + ad + str); 56 } 57 }
EventMask
1 using UnityEngine; 2 using System.Collections; 3 public class LayerCullDistances_ts : MonoBehaviour 4 { 5 public Transform cb1; 6 void Start() 7 { 8 //定义大小为32的一维数组,用来存储所有层的剔除距离 9 float[] distances = new float[32]; 10 //设置第9层的剔除距离 11 distances[8] = Vector3.Distance(transform.position, cb1.position); 12 //将数组赋给摄像机的layerCullDistances 13 camera.layerCullDistances = distances; 14 } 15 void Update() 16 { 17 //摄像机远离物体 18 transform.Translate(transform.right * Time.deltaTime); 19 } 20 }
LayerCullDistances
1 using UnityEngine; 2 using System.Collections; 3 4 public class layerCullSpherical_ts : MonoBehaviour 5 { 6 public Transform cb1, cb2, cb3; 7 void Start() 8 { 9 //定义大小为32的一维数组,用来存储所有层的剔除距离 10 float[] distances = new float[32]; 11 //设置第9层的剔除距离 12 distances[8] = Vector3.Distance(transform.position, cb1.position); 13 //将数组赋给摄像机的layerCullDistances 14 camera.layerCullDistances = distances; 15 //打印出三个物体距离摄像机的距离 16 Debug.Log("Cube1距离摄像机的距离:" + Vector3.Distance(transform.position, cb1.position)); 17 Debug.Log("Cube2距离摄像机的距离:" + Vector3.Distance(transform.position, cb2.position)); 18 Debug.Log("Cube3距离摄像机的距离:" + Vector3.Distance(transform.position, cb3.position)); 19 } 20 21 void OnGUI() 22 { 23 //使用球形距离剔除 24 if (GUI.Button(new Rect(10.0f, 10.0f, 180.0f, 45.0f), "use layerCullSpherical")) 25 { 26 camera.layerCullSpherical = true; 27 } 28 //取消球形距离剔除 29 if (GUI.Button(new Rect(10.0f, 60.0f, 180.0f, 45.0f), "unuse layerCullSpherical")) 30 { 31 camera.layerCullSpherical = false; 32 } 33 } 34 }
layerCullSpherical
1 using UnityEngine; 2 using System.Collections; 3 4 public class orthographic_ts : MonoBehaviour 5 { 6 float len = 5.5f; 7 void OnGUI() 8 { 9 if (GUI.Button(new Rect(10.0f, 10.0f, 120.0f, 45.0f), "正交投影")) 10 { 11 camera.orthographic = true; 12 len = 5.5f; 13 } 14 if (GUI.Button(new Rect(150.0f, 10.0f, 120.0f, 45.0f), "透视投影")) 15 { 16 camera.orthographic = false; 17 len = 60.0f; 18 } 19 if (camera.orthographic) 20 { 21 //正交投影模式下,物体没有远大近小的效果, 22 //orthographicSize的大小无限制,当orthographicSize为负数时视口的内容会颠倒, 23 //orthographicSize的绝对值为摄像机视口的高度值,即上下两条边之间的距离 24 len = GUI.HorizontalSlider(new Rect(10.0f, 60.0f, 300.0f, 45.0f), len, -20.0f, 20.0f); 25 camera.orthographicSize = len; 26 } 27 else 28 { 29 //透视投影模式下,物体有远大近小的效果, 30 //fieldOfViewd的取值范围为1.0-179.0 31 len = GUI.HorizontalSlider(new Rect(10.0f, 60.0f, 300.0f, 45.0f), len, 1.0f, 179.0f); 32 camera.fieldOfView = len; 33 } 34 //实时显示len大小 35 GUI.Label(new Rect(320.0f, 60.0f, 120.0f, 45.0f), len.ToString()); 36 } 37 }
orthographic
1 using UnityEngine; 2 using System.Collections; 3 4 public class PixelRect_ts : MonoBehaviour 5 { 6 int which_change = -1; 7 float temp_x = 0.0f, temp_y = 0.0f; 8 void Update() 9 { 10 //Screen.width和Screen.height为模拟硬件屏幕的宽高值, 11 //其返回值不随camera.pixelWidth和camera.pixelHeight的改变而改变 12 Debug.Log("Screen.width:" + Screen.width); 13 Debug.Log("Screen.height:" + Screen.height); 14 Debug.Log("pixelWidth:" + camera.pixelWidth); 15 Debug.Log("pixelHeight:" + camera.pixelHeight); 16 //通过改变Camera的坐标位置而改变视口的区间 17 if (which_change == 0) 18 { 19 if (camera.pixelWidth > 1.0f) 20 { 21 temp_x += Time.deltaTime * 20.0f; 22 } 23 //取消以下注释察看平移状况 24 //if (camera.pixelHeight > 1.0f) 25 //{ 26 // temp_y += Time.deltaTime * 20.0f; 27 //} 28 camera.pixelRect = new Rect(temp_x, temp_y, camera.pixelWidth, camera.pixelHeight); 29 } 30 //通过改变Camera的视口宽度和高度来改变视口的区间 31 else if (which_change == 1) 32 { 33 if (camera.pixelWidth > 1.0f) 34 { 35 temp_x = camera.pixelWidth - Time.deltaTime * 20.0f; 36 } 37 //取消以下注释察看平移状况 38 //if (camera.pixelHeight > 1.0f) 39 //{ 40 // temp_y = camera.pixelHeight - Time.deltaTime * 20.0f; 41 //} 42 camera.pixelRect = new Rect(0, 0, temp_x, temp_y); 43 } 44 } 45 void OnGUI() 46 { 47 if (GUI.Button(new Rect(10.0f, 10.0f, 200.0f, 45.0f), "视口改变方式1")) 48 { 49 camera.rect = new Rect(0.0f, 0.0f, 1.0f, 1.0f); 50 which_change = 0; 51 temp_x = 0.0f; 52 temp_y = 0.0f; 53 } 54 if (GUI.Button(new Rect(10.0f, 60.0f, 200.0f, 45.0f), "视口改变方式2")) 55 { 56 camera.rect = new Rect(0.0f, 0.0f, 1.0f, 1.0f); 57 which_change = 1; 58 temp_x = 0.0f; 59 temp_y = camera.pixelHeight; 60 } 61 if (GUI.Button(new Rect(10.0f, 110.0f, 200.0f, 45.0f), "视口还原")) 62 { 63 camera.rect = new Rect(0.0f, 0.0f, 1.0f, 1.0f); 64 which_change = -1; 65 } 66 } 67 }
PixelRect
1 using UnityEngine; 2 using System.Collections; 3 4 public class ProjectionMatrix_ts : MonoBehaviour 5 { 6 public Transform sp, cb; 7 public Matrix4x4 originalProjection; 8 float q=0.1f;//晃动振幅 9 float p=1.5f;//晃动频率 10 int which_change = -1; 11 void Start() 12 { 13 //记录原始投影矩阵 14 originalProjection = camera.projectionMatrix; 15 } 16 void Update() 17 { 18 sp.RotateAround(cb.position, cb.up, 45.0f * Time.deltaTime); 19 Matrix4x4 pr = originalProjection; 20 switch (which_change) 21 { 22 case -1: 23 break; 24 case 0: 25 //绕摄像机X轴晃动 26 pr.m11 += Mathf.Sin(Time.time * p) * q; 27 break; 28 case 1: 29 //绕摄像机Y轴晃动 30 pr.m01 += Mathf.Sin(Time.time * p) * q; 31 break; 32 case 2: 33 //绕摄像机Z轴晃动 34 pr.m10 += Mathf.Sin(Time.time * p) * q; 35 break; 36 case 3: 37 //绕摄像机左右移动 38 pr.m02 += Mathf.Sin(Time.time * p) * q; 39 break; 40 case 4: 41 //摄像机视口放缩运动 42 pr.m00 += Mathf.Sin(Time.time * p) * q; 43 break; 44 } 45 //设置Camera的变换矩阵 46 camera.projectionMatrix = pr; 47 } 48 void OnGUI() 49 { 50 if (GUI.Button(new Rect(10.0f, 10.0f, 200.0f, 45.0f), "绕摄像机X轴晃动")) 51 { 52 camera.ResetProjectionMatrix(); 53 which_change = 0; 54 } 55 if (GUI.Button(new Rect(10.0f, 60.0f, 200.0f, 45.0f), "绕摄像机Y轴晃动")) 56 { 57 camera.ResetProjectionMatrix(); 58 which_change = 1; 59 } 60 if (GUI.Button(new Rect(10.0f, 110.0f, 200.0f, 45.0f), "绕摄像机Z轴晃动")) 61 { 62 camera.ResetProjectionMatrix(); 63 which_change = 2; 64 } 65 if (GUI.Button(new Rect(10.0f, 160.0f, 200.0f, 45.0f), "绕摄像机左右移动")) 66 { 67 camera.ResetProjectionMatrix(); 68 which_change = 3; 69 } 70 if (GUI.Button(new Rect(10.0f, 210.0f, 200.0f, 45.0f), "视口放缩运动")) 71 { 72 camera.ResetProjectionMatrix(); 73 which_change = 4; 74 } 75 } 76 }
ProjectionMatrix
1 using UnityEngine; 2 using System.Collections; 3 4 public class Rect_ts : MonoBehaviour 5 { 6 int which_change = -1; 7 float temp_x = 0.0f, temp_y = 0.0f; 8 void Update() 9 { 10 //视口平移 11 if (which_change == 0) 12 { 13 if (camera.rect.x < 1.0f) 14 { 15 //沿着X轴平移 16 temp_x = camera.rect.x + Time.deltaTime * 0.2f; 17 } 18 //取消下面注释察看平移的变化 19 //if (camera.rect.y< 1.0f) 20 //{ 21 //沿着Y轴平移 22 // temp_y = camera.rect.y + Time.deltaTime * 0.2f; 23 //} 24 camera.rect = new Rect(temp_x, temp_y, camera.rect.width, camera.rect.height); 25 } 26 //视口放缩 27 else if (which_change == 1) 28 { 29 if (camera.rect.width > 0.0f) 30 { 31 //沿着X轴放缩 32 temp_x = camera.rect.width - Time.deltaTime * 0.2f; 33 } 34 if (camera.rect.height > 0.0f) 35 { 36 //沿着Y轴放缩 37 temp_y = camera.rect.height - Time.deltaTime * 0.2f; 38 } 39 camera.rect = new Rect(camera.rect.x, camera.rect.y, temp_x, temp_y); 40 } 41 } 42 void OnGUI() 43 { 44 if (GUI.Button(new Rect(10.0f, 10.0f, 200.0f, 45.0f), "视口平移")) 45 { 46 //重置视口 47 camera.rect = new Rect(0.0f, 0.0f, 1.0f, 1.0f); 48 which_change = 0; 49 temp_y = 0.0f; 50 } 51 if (GUI.Button(new Rect(10.0f, 60.0f, 200.0f, 45.0f), "视口放缩")) 52 { 53 camera.rect = new Rect(0.0f, 0.0f, 1.0f, 1.0f); 54 which_change = 1; 55 } 56 if (GUI.Button(new Rect(10.0f, 110.0f, 200.0f, 45.0f), "视口还原")) 57 { 58 camera.rect = new Rect(0.0f, 0.0f, 1.0f, 1.0f); 59 which_change = -1; 60 } 61 } 62 }
Rect
1 using UnityEngine; 2 using System.Collections; 3 4 public class renderingPath_ts : MonoBehaviour 5 { 6 void OnGUI() 7 { 8 if (GUI.Button(new Rect(10.0f, 10.0f, 120.0f, 45.0f), "UsePlayerSettings")) 9 { 10 camera.renderingPath = RenderingPath.UsePlayerSettings; 11 } 12 if (GUI.Button(new Rect(10.0f, 60.0f, 120.0f, 45.0f), "VertexLit")) 13 { 14 camera.renderingPath = RenderingPath.VertexLit; 15 } 16 if (GUI.Button(new Rect(10.0f, 110.0f, 120.0f, 45.0f), "Forward")) 17 { 18 camera.renderingPath = RenderingPath.Forward; 19 } 20 if (GUI.Button(new Rect(10.0f, 160.0f, 120.0f, 45.0f), "DeferredLighting")) 21 { 22 camera.renderingPath = RenderingPath.DeferredLighting; 23 } 24 } 25 }
renderingPath
1 using UnityEngine; 2 using System.Collections; 3 4 public class Target_ts : MonoBehaviour { 5 public Transform ts; 6 void Update () { 7 transform.RotateAround(ts.position,ts.up,30.0f*Time.deltaTime); 8 } 9 }
Target
1 using UnityEngine; 2 using System.Collections; 3 4 public class WorldToCameraMatrix_ts : MonoBehaviour 5 { 6 public Camera c_test; 7 void OnGUI() 8 { 9 if (GUI.Button(new Rect(10.0f, 10.0f, 200.0f, 45.0f), "更改变换矩阵")) 10 { 11 //使用c_test的变换矩阵 12 camera.worldToCameraMatrix = c_test.worldToCameraMatrix; 13 //也可使用如下代码实现同样功能 14 // camera.CopyFrom(c_test); 15 } 16 if (GUI.Button(new Rect(10.0f, 60.0f, 200.0f, 45.0f), "重置变换矩阵")) 17 { 18 camera.ResetWorldToCameraMatrix(); 19 } 20 } 21 }
WorldToCameraMatrix
1 using UnityEngine; 2 using System.Collections; 3 4 public class RenderToCubemap_ts : MonoBehaviour 5 { 6 public Cubemap cp; 7 void Start() 8 { 9 camera.RenderToCubemap(cp); 10 } 11 }
RenderToCubemap
1 using UnityEngine; 2 using System.Collections; 3 4 public class RenderWithShader_ts : MonoBehaviour 5 { 6 bool is_use = false; 7 void OnGUI() 8 { 9 if (is_use) 10 { 11 //使用高光shader:Specular来渲染Camera 12 camera.RenderWithShader(Shader.Find("Specular"), "RenderType"); 13 } 14 if (GUI.Button(new Rect(10.0f, 10.0f, 300.0f, 45.0f), "使用RenderWithShader启用高光")) 15 { 16 //RenderWithShader每调用一次只渲染一帧,所以不可将其直接放到这儿 17 //camera.RenderWithShader(Shader.Find("Specular"), "RenderType"); 18 is_use = true; 19 } 20 if (GUI.Button(new Rect(10.0f, 60.0f, 300.0f, 45.0f), "使用SetReplacementShader启用高光")) 21 { 22 //SetReplacementShader方法用来替换已有shader,调用一次即可 23 camera.SetReplacementShader(Shader.Find("Specular"), "RenderType"); 24 is_use = false; 25 } 26 if (GUI.Button(new Rect(10.0f, 110.0f, 300.0f, 45.0f), "关闭高光")) 27 { 28 camera.ResetReplacementShader(); 29 is_use = false; 30 } 31 } 32 }
RenderWithShader
1 using UnityEngine; 2 using System.Collections; 3 4 public class ScreenPointToRay_ts : MonoBehaviour 5 { 6 Ray ray; 7 RaycastHit hit; 8 Vector3 v3 = new Vector3(Screen.width / 2.0f, Screen.height / 2.0f, 0.0f); 9 Vector3 hitpoint = Vector3.zero; 10 void Update() 11 { 12 //射线沿着屏幕X轴从左向右循环扫描 13 v3.x = v3.x >= Screen.width ? 0.0f : v3.x + 1.0f; 14 //生成射线 15 ray = camera.ScreenPointToRay(v3); 16 if (Physics.Raycast(ray, out hit, 100.0f)) 17 { 18 //绘制线,在Scene视图中可见 19 Debug.DrawLine(ray.origin, hit.point, Color.green); 20 //输出射线探测到的物体的名称 21 Debug.Log("射线探测到的物体名称:" + hit.transform.name); 22 } 23 } 24 }
ScreenPointToRay
1 using UnityEngine; 2 using System.Collections; 3 4 public class ScreenToViewportPoint_ts : MonoBehaviour 5 { 6 void Start() 7 { 8 transform.position = new Vector3(0.0f, 0.0f, 1.0f); 9 transform.rotation = Quaternion.identity; 10 //从屏幕的实际坐标点向视口的单位化比例值转换 11 Debug.Log("1:" + camera.ScreenToViewportPoint(new Vector3(Screen.width / 2.0f, Screen.height / 2.0f, 100.0f))); 12 //从视口的单位化比例值向屏幕的实际坐标点转换 13 Debug.Log("2:" + camera.ViewportToScreenPoint(new Vector3(0.5f, 0.5f, 100.0f))); 14 Debug.Log("屏幕宽:" + Screen.width + " 屏幕高:" + Screen.height); 15 } 16 }
ScreenToViewportPoint
1 using UnityEngine; 2 using System.Collections; 3 4 public class ScreenToWorldPoint_ts : MonoBehaviour 5 { 6 void Start() 7 { 8 transform.position = new Vector3(0.0f, 0.0f, 1.0f); 9 camera.fieldOfView = 60.0f; 10 camera.aspect = 16.0f / 10.0f; 11 //Z轴前方100处对应的屏幕的左下角的世界坐标值 12 Debug.Log("1:" + camera.ScreenToWorldPoint(new Vector3(0.0f, 0.0f, 100.0f))); 13 //Z轴前方100处对应的屏幕的中间的世界坐标值 14 Debug.Log("2:" + camera.ScreenToWorldPoint(new Vector3(Screen.width / 2.0f, Screen.height / 2.0f, 100.0f))); 15 //Z轴前方100处对应的屏幕的右上角的世界坐标值 16 Debug.Log("3:" + camera.ScreenToWorldPoint(new Vector3(Screen.width, Screen.height, 100.0f))); 17 } 18 }
ScreenToWorldPoint
1 using UnityEngine; 2 using System.Collections; 3 4 public class SetTargetBuffers_ts : MonoBehaviour 5 { 6 //声明两个RendererTexture变量 7 public RenderTexture RT_1, RT_2; 8 public Camera c;//指定Camera 9 10 void OnGUI() 11 { 12 //设置RT_1的buffer为摄像机c的渲染 13 if (GUI.Button(new Rect(10.0f, 10.0f, 180.0f, 45.0f), "set target buffers")) 14 { 15 c.SetTargetBuffers(RT_1.colorBuffer, RT_1.depthBuffer); 16 } 17 //设置RT_2的buffer为摄像机c的渲染,此时RT_1的buffer变为场景中Camera1的渲染 18 if (GUI.Button(new Rect(10.0f, 60.0f, 180.0f, 45.0f), "Reset target buffers")) 19 { 20 c.SetTargetBuffers(RT_2.colorBuffer, RT_2.depthBuffer); 21 } 22 } 23 }
SetTargetBuffers
1 using UnityEngine; 2 using System.Collections; 3 4 public class ViewportPointToRay_ts : MonoBehaviour 5 { 6 Ray ray;//射线 7 RaycastHit hit; 8 Vector3 v3 = new Vector3(0.5f, 0.5f, 0.0f); 9 Vector3 hitpoint = Vector3.zero; 10 void Update() 11 { 12 //射线沿着屏幕X轴从左向右循环扫描 13 v3.x = v3.x >= 1.0f ? 0.0f : v3.x + 0.002f; 14 //生成射线 15 ray = camera.ViewportPointToRay(v3); 16 if (Physics.Raycast(ray, out hit, 100.0f)) 17 { 18 //绘制线,在Scene视图中可见 19 Debug.DrawLine(ray.origin, hit.point, Color.green); 20 //输出射线探测到的物体的名称 21 Debug.Log("射线探测到的物体名称:" + hit.transform.name); 22 } 23 } 24 }
ViewportPointToRay
1 using UnityEngine; 2 using System.Collections; 3 4 public class ViewportToWorldPoint_ts : MonoBehaviour 5 { 6 void Start() 7 { 8 transform.position = new Vector3(1.0f, 0.0f, 1.0f); 9 camera.fieldOfView = 60.0f; 10 camera.aspect = 16.0f / 10.0f; 11 //屏幕左下角 12 Debug.Log("1:" + camera.ViewportToWorldPoint(new Vector3(0.0f, 0.0f, 100.0f))); 13 //屏幕中间 14 Debug.Log("2:" + camera.ViewportToWorldPoint(new Vector3(0.5f, 0.5f, 100.0f))); 15 //屏幕右上角 16 Debug.Log("3:" + camera.ViewportToWorldPoint(new Vector3(1.0f, 1.0f, 100.0f))); 17 } 18 }
ViewportToWorldPoint
1 using UnityEngine; 2 using System.Collections; 3 4 public class WorldToScreenPoint_ts : MonoBehaviour 5 { 6 public Transform cb, sp; 7 public Texture2D t2; 8 Vector3 v3 = Vector3.zero; 9 float sg; 10 void Start() 11 { 12 //记录屏幕高度 13 sg = Screen.height; 14 } 15 void Update() 16 { 17 //sp绕着cb的Y轴旋转 18 sp.RotateAround(cb.position, cb.up, 30.0f * Time.deltaTime); 19 //获取sp在屏幕上的坐标点 20 v3 = camera.WorldToScreenPoint(sp.position); 21 } 22 void OnGUI() 23 { 24 //绘制纹理 25 GUI.DrawTexture(new Rect(0.0f, sg - v3.y, v3.x, sg), t2); 26 } 27 }
WorldToScreenPoint
1 using UnityEngine; 2 using System.Collections; 3 4 public class WorldToViewportPoint_ts : MonoBehaviour 5 { 6 public Transform cb, sp; 7 public Texture2D t2; 8 Vector3 v3 = Vector3.zero; 9 float sw, sh; 10 void Start() 11 { 12 //记录屏幕的宽度和高度 13 sw = Screen.width; 14 sh = Screen.height; 15 } 16 void Update() 17 { 18 //物体sp始终绕cb的Y轴旋转 19 sp.RotateAround(cb.position, cb.up, 30.0f * Time.deltaTime); 20 //记录sp映射到屏幕上的比例值 21 v3 = camera.WorldToViewportPoint(sp.position); 22 } 23 void OnGUI() 24 { 25 //绘制纹理,由于方法WorldToViewportPoint的返回值的y分量是从屏幕下方向上方递增的, 26 //所以需要先计算1.0f - v3.y的值,然后再和sh相乘。 27 GUI.DrawTexture(new Rect(0.0f, sh * (1.0f - v3.y), sw * v3.x, sh), t2); 28 } 29 }
WorldToViewportPoint
1 using UnityEngine; 2 using System.Collections; 3 4 public class Compare_ts : MonoBehaviour 5 { 6 Vector3 v1; 7 void Start() 8 { 9 v1 = transform.position; 10 } 11 void OnGUI() 12 { 13 //设置Camera视口宽高比例为2:1,点击此按钮后更改Game视图中不同的aspect值, 14 //尽管Scene视图中Camera视口的宽高比会跟着改变,但实际Camera视口的内容依然是按照2:1 15 //的比例所所获取的,不同的屏幕显示相同的内容会发生变形。 16 if (GUI.Button(new Rect(10.0f, 10.0f, 200.0f, 45.0f), "Camera视口宽高比例2:1")) 17 { 18 camera.aspect = 2.0f; 19 transform.position = v1; 20 } 21 if (GUI.Button(new Rect(10.0f, 60.0f, 200.0f, 45.0f), "Camera视口宽高比例1:2")) 22 { 23 camera.aspect = 0.5f; 24 //更改Camera坐标,使被拉伸后的物体显示出来 25 transform.position = new Vector3(v1.x, v1.y, 333.2f); 26 } 27 //恢复aspect的默认设置,即屏幕比例和Camera视口比例保持一致 28 if (GUI.Button(new Rect(10.0f, 110.0f, 200.0f, 45.0f), "使用Game面板中aspect的选择")) 29 { 30 camera.ResetAspect(); 31 transform.position = v1; 32 } 33 } 34 }
Compare
3 GameObject类
1 using UnityEngine; 2 using System.Collections; 3 4 public class ActiveSelf_ts : MonoBehaviour { 5 public GameObject cube1, cube2, cube3; 6 void Start () { 7 //对cube2设置为false,其他设置为true 8 cube1.SetActive(true); 9 cube2.SetActive(false); 10 cube3.SetActive(true); 11 12 Debug.Log("activeSelf:"); 13 //尽管cube2被设置为false,但其子类cube3的activeSelf返回值仍然为true 14 Debug.Log("cube1.activeSelf:" + cube1.activeSelf); 15 Debug.Log("cube2.activeSelf:" + cube2.activeSelf); 16 Debug.Log("cube3.activeSelf:" + cube3.activeSelf); 17 18 Debug.Log("\nactiveInHierarchy:"); 19 //cube2和cube3的activeInHierarchy返回值都为false。 20 Debug.Log("cube1.activeInHierarchy:" + cube1.activeInHierarchy); 21 Debug.Log("cube2.activeInHierarchy:" + cube2.activeInHierarchy); 22 Debug.Log("cube3.activeInHierarchy:" + cube3.activeInHierarchy); 23 } 24 }
ActiveSelf
1 using UnityEngine; 2 using System.Collections; 3 4 public class Constructors_ts : MonoBehaviour { 5 void Start () { 6 //使用构造函数GameObject (name : String) 7 GameObject g1 = new GameObject("G1"); 8 g1.AddComponent<Rigidbody>(); 9 //使用构造函数GameObject () 10 GameObject g2 = new GameObject(); 11 g2.AddComponent<FixedJoint>(); 12 //使用构造函数GameObject (name : String, params components : Type[]) 13 GameObject g3 = new GameObject("G3",typeof(MeshRenderer),typeof(Rigidbody),typeof(SpringJoint)); 14 15 Debug.Log("g1 name:" + g1.name + "\nPosition:" + g1.transform.position); 16 Debug.Log("g2 name:" + g2.name + "\nPosition:" + g2.transform.position); 17 Debug.Log("g3 name:" + g3.name + "\nPosition:" + g3.transform.position); 18 } 19 }
Constructors
1 using UnityEngine; 2 using System.Collections; 3 4 public class GetComponent_ts : MonoBehaviour { 5 void Start () { 6 Debug.Log("以下是GetComponent的相关使用代码。\nGetComponent方法用来获取当前GameObject中符合Type类型的第一个组件。"); 7 //GetComponent (type : Type) 8 Rigidbody rb = GetComponent(typeof(Rigidbody))as Rigidbody; 9 Debug.Log("使用GetComponent (type : Type)获取Rigidbody:" + rb.GetInstanceID()); 10 11 //GetComponent.<T>() 12 rb=GetComponent<Rigidbody>(); 13 Debug.Log("使用GetComponent.<T>()获取Rigidbody:" + rb.GetInstanceID()); 14 15 //GetComponent (type : String) 16 rb = GetComponent("Rigidbody") as Rigidbody; 17 Debug.Log("使用GetComponent (type : String)获取Rigidbody:" + rb.GetInstanceID()); 18 19 Debug.Log("以下是GetComponentInChildren的相关使用代码。\nGetComponentInChildren方法用来获取当前GameObject的所有子类中中符合Type类型的第一个组件。"); 20 21 //GetComponentInChildren (type : Type) 22 rb = GetComponentInChildren(typeof(Rigidbody)) as Rigidbody; 23 Debug.Log("使用GetComponentInChildren (type : Type)获取Rigidbody:" + rb.name); 24 25 //GetComponentInChildren.<T> () 26 rb=GetComponentInChildren<Rigidbody>(); 27 Debug.Log("使用GetComponentInChildren.<T>()获取Rigidbody:" + rb.name); 28 29 Debug.Log("以下是GetComponents的相关使用代码。\nGetComponents方法用来获取当前GameObject中符合Type类型的所有组件。"); 30 31 //GetComponents (type : Type) 32 Component[] cjs = GetComponents(typeof(ConfigurableJoint)) as Component[]; 33 foreach(ConfigurableJoint cj in cjs){ 34 Debug.Log("使用GetComponents (type : Type)获取ConfigurableJoint:" + cj.GetInstanceID()); 35 } 36 37 //GetComponents.<T> () 38 cjs = GetComponents<ConfigurableJoint>(); 39 foreach (ConfigurableJoint cj in cjs) 40 { 41 Debug.Log("使用GetComponents.<T>()获取ConfigurableJoint:" + cj.GetInstanceID()); 42 } 43 44 Debug.Log("以下是GetComponentsInChildren的相关使用代码。\nGetComponentsInChildren方法用来获取当前GameObject的子类中符合Type类型的所有组件。"); 45 46 //GetComponentsInChildren(type: Type, includeInactive: boolean = false) 47 cjs = GetComponentsInChildren(typeof(ConfigurableJoint), false) as Component[]; 48 foreach (ConfigurableJoint cj in cjs) 49 { 50 Debug.Log("使用GetComponentsInChildren(type: Type, false)获取ConfigurableJoint:" + cj.name); 51 } 52 53 cjs = GetComponentsInChildren(typeof(ConfigurableJoint), true) as Component[]; 54 foreach (ConfigurableJoint cj in cjs) 55 { 56 Debug.Log("使用GetComponentsInChildren(type: Type, true)获取ConfigurableJoint:" + cj.name); 57 } 58 59 //GetComponentsInChildren.<T> (includeInactive : boolean) 60 cjs = GetComponentsInChildren<ConfigurableJoint>(true); 61 foreach (ConfigurableJoint cj in cjs) 62 { 63 Debug.Log("使用GetComponentsInChildren.<T>(includeInactive : boolean)获取ConfigurableJoint:" + cj.name); 64 } 65 66 //GetComponentsInChildren.<T> () 67 cjs = GetComponentsInChildren<ConfigurableJoint>(); 68 foreach (ConfigurableJoint cj in cjs) 69 { 70 Debug.Log("使用GetComponentsInChildren.<T>()获取ConfigurableJoint:" + cj.name); 71 } 72 } 73 }
GetComponent
1 using UnityEngine; 2 using System.Collections; 3 4 public class SendMessage_ts : MonoBehaviour { 5 void Start () { 6 //向子类及自己发送信息 7 //gameObject.BroadcastMessage("GetParentMessage",gameObject.name+":use BroadcastMessage send!"); 8 //向自己发送信息 9 gameObject.SendMessage("GetSelfMessage",gameObject.name+":use SendMessage send!"); 10 ////向父类及自己发送信息 11 //gameObject.SendMessageUpwards("GetChildrenMessage",gameObject.name+":use SendMessageUpwards send!"); 12 } 13 //一个接受父类发送信息的方法 14 private void GetParentMessage(string str){ 15 Debug.Log(gameObject.name + "收到父类发送的消息:" + str); 16 } 17 //一个接受自身发送信息的方法 18 private void GetSelfMessage(string str) 19 { 20 Debug.Log(gameObject.name + "收到自身发送的消息:" + str); 21 } 22 //一个接受子类发送信息的方法 23 private void GetChildrenMessage(string str) 24 { 25 Debug.Log(gameObject.name + "收到子类发送的消息:" + str); 26 } 27 }
SendMessage
1 using UnityEngine; 2 using System.Collections; 3 4 public class CreatePrimitive_ts : MonoBehaviour 5 { 6 void Start() 7 { 8 //使用GameObject.CreatePrimitive方法创建GameObject 9 GameObject g1 = GameObject.CreatePrimitive(PrimitiveType.Sphere); 10 g1.name = "G1"; 11 g1.tag = "sphere_Tag"; 12 //使用 AddComponent (className : String)方法添加组件 13 g1.AddComponent("SpringJoint"); 14 //使用AddComponent (componentType : Type)方法添加组件 15 g1.AddComponent(typeof(GUITexture)); 16 g1.transform.position = Vector3.zero; 17 18 GameObject g2 = GameObject.CreatePrimitive(PrimitiveType.Sphere); 19 g2.name = "G2"; 20 g2.tag = "sphere_Tag"; 21 //使用AddComponent.<T>()方法添加组件 22 g2.AddComponent<Rigidbody>(); 23 g2.transform.position = 2.0f * Vector3.right; 24 g2.GetComponent<Rigidbody>().useGravity = false; 25 26 GameObject g3 = GameObject.CreatePrimitive(PrimitiveType.Sphere); 27 g3.name = "G1"; 28 g3.tag = "sphere_Tag"; 29 g3.transform.position = 4.0f * Vector3.right; 30 31 //使用GameObject.Find类方法获取GameObject,返回符合条件的第一个对象 32 Debug.Log("use Find:" + GameObject.Find("G1").transform.position); 33 //使用GameObject.FindGameObjectWithTag类方法获取GameObject,返回符合条件的第一个对象 34 Debug.Log("use FindGameObjectWithTag:" + GameObject.FindGameObjectWithTag("sphere_Tag").transform.position); 35 //使用GameObject.FindGameObjectsWithTag类方法获取GameObject,返回符合条件的所有对象 36 GameObject[] gos = GameObject.FindGameObjectsWithTag("sphere_Tag"); 37 foreach (GameObject go in gos) 38 { 39 Debug.Log("use FindGameObjectsWithTag:" + go.name + ":" + go.transform.position); 40 } 41 42 g3.transform.parent = g2.transform; 43 g2.transform.parent = g1.transform; 44 45 Debug.Log("use Find again1:" + GameObject.Find("G1").transform.position); 46 //使用带"/"限定条件的方式查找GameObject, 47 //此处返回的对象需其父类为G2,且G2的父类名为G1, 48 //注意与上面不带"/"限定条件返回的对象的区别。 49 Debug.Log("use Find again2:" + GameObject.Find("/G1/G2/G1").transform.position); 50 } 51 }
CreatePrimitive
1 using UnityEngine; 2 using System.Collections; 3 4 public class BroadcastMessage_ts : MonoBehaviour 5 { 6 void Start() 7 { 8 gameObject.BroadcastMessage("GetParentMessage", gameObject.name + ":use BroadcastMessage send!"); 9 } 10 private void GetParentMessage(string str) 11 { 12 Debug.Log(gameObject.name + "收到父类发送的消息:" + str); 13 } 14 15 private void GetSelfMessage(string str) 16 { 17 Debug.Log(gameObject.name + "收到自身发送的消息:" + str); 18 } 19 20 private void GetChildrenMessage(string str) 21 { 22 Debug.Log(gameObject.name + "收到子类发送的消息:" + str); 23 } 24 }
BroadcastMessage
1 using UnityEngine; 2 using System.Collections; 3 4 public class GameObjectAndComponent_ts : MonoBehaviour { 5 public GameObject sp; 6 void Start () { 7 //以下三种表达方式功能一样,都返回当前脚本所在GameObject对象中的Rigidbody组件 8 Rigidbody rb1 = rigidbody; 9 Rigidbody rb2 = GetComponent<Rigidbody>(); 10 Rigidbody rb3 = rigidbody.GetComponent<Rigidbody>(); 11 Debug.Log("rb1的InstanceID:" + rb1.GetInstanceID()); 12 Debug.Log("rb2的InstanceID:" + rb2.GetInstanceID()); 13 Debug.Log("rb3的InstanceID:" + rb3.GetInstanceID()); 14 15 //使用前置引用获取引用对象的Rigidbody组件 16 Debug.Log("前置引用sp对象中Rigidbody的InstanceID:"+sp.GetComponent<Rigidbody>().GetInstanceID()); 17 } 18 }
GameObjectAndComponent
1 using UnityEngine; 2 using System.Collections; 3 4 public class SendMessageUpward_ts : MonoBehaviour { 5 void Start () { 6 gameObject.SendMessageUpwards("GetChildrenMessage", gameObject.name + ":use SendMessageUpwards send!"); 7 } 8 private void GetParentMessage(string str) 9 { 10 Debug.Log(gameObject.name + "收到父类发送的消息:" + str); 11 } 12 13 private void GetSelfMessage(string str) 14 { 15 Debug.Log(gameObject.name + "收到自身发送的消息:" + str); 16 } 17 18 private void GetChildrenMessage(string str) 19 { 20 Debug.Log(gameObject.name + "收到子类发送的消息:" + str); 21 } 22 }
SendMessageUpward
4 HideFlags类
1 using UnityEngine; 2 using System.Collections; 3 4 public class DontSave_ts : MonoBehaviour { 5 public GameObject go; 6 public Transform t; 7 void Start() 8 { 9 //GameObject对象使用HideFlags.DontSave可以在新scene中被保留 10 go.hideFlags = HideFlags.DontSave; 11 GameObject Pl = GameObject.CreatePrimitive(PrimitiveType.Plane); 12 Pl.hideFlags = HideFlags.DontSave; 13 //不可以对GameObject的组件设置HideFlags.DontSave,否则无效 14 Transform tf = Instantiate(t, go.transform.position + new Vector3(2.0f, 0.0f, 0.0f), Quaternion.identity) as Transform; 15 tf.hideFlags = HideFlags.DontSave; 16 //导入名为newScene_unity的新scene 17 Application.LoadLevel("newScene2_unity"); 18 } 19 }
DontSave
1 using UnityEngine; 2 using System.Collections; 3 4 public class HideInHierarchy_ts : MonoBehaviour 5 { 6 public GameObject go, sub; 7 public Transform t; 8 void Awake() 9 { 10 //go、sub、gameObject为已存在对象,需在Awake方法中使用HideFlags.HideInHierarchy 11 go.hideFlags = HideFlags.HideInHierarchy; 12 sub.hideFlags = HideFlags.HideInHierarchy; 13 gameObject.hideFlags = HideFlags.HideInHierarchy; 14 } 15 16 void Start() 17 { 18 //Pl、tf是在代码中创建的对象,可以在任何方法中使用HideFlags.HideInHierarchy 19 GameObject Pl = GameObject.CreatePrimitive(PrimitiveType.Plane); 20 Pl.hideFlags = HideFlags.HideInHierarchy; 21 Transform tf = Instantiate(t, go.transform.position + new Vector3(2, 0.0f, 0.0f), Quaternion.identity) as Transform; 22 tf.hideFlags = HideFlags.HideInHierarchy; 23 } 24 }
HideInHierarchy
1 using UnityEngine; 2 using System.Collections; 3 4 public class HideInInspector_td : MonoBehaviour { 5 public GameObject go; 6 public Transform t; 7 void Start() 8 { 9 //go、gameObject、Pl都是GameObject对象,使用HideFlags.HideInInspector后, 10 //其所有组件将在Inspector面板中隐藏, 11 //但并不影响其子类在Inspector面板中的显示。 12 go.hideFlags = HideFlags.HideInInspector; 13 gameObject.hideFlags = HideFlags.HideInInspector; 14 GameObject Pl = GameObject.CreatePrimitive(PrimitiveType.Plane); 15 Pl.hideFlags = HideFlags.HideInInspector; 16 //tf为Transform对象,使用HideFlags.HideInInspector后, 17 //tf对应的GameObject的Transform组件将在Inspector面板中隐藏, 18 //但GameObject的其他组件扔可在Inspector面板中显示。 19 Transform tf = Instantiate(t, go.transform.position + new Vector3(2.0f, 0.0f, 0.0f), Quaternion.identity) as Transform; 20 tf.hideFlags = HideFlags.HideInInspector; 21 } 22 }
HideInInspector
1 using UnityEngine; 2 using System.Collections; 3 4 public class NewScene_ts : MonoBehaviour { 5 void Start () { 6 Debug.Log("这是NewScene!"); 7 //导入名为newScene_unity2的新scene 8 Application.LoadLevel("newScene2_unity"); 9 } 10 }
NewScene
1 using UnityEngine; 2 using System.Collections; 3 4 public class NewScene2_ts : MonoBehaviour 5 { 6 GameObject cube, plane; 7 void Start() 8 { 9 Debug.Log("这是NewScene2!"); 10 } 11 //当程序退出时用DestroyImmediate()销毁被HideFlags.DontSave标识的对象, 12 //否则即使程序已经退出,被HideFlags.DontSave标识的对象依然在Hierarchy面板中, 13 //即每运行一次程序就会产生多余对象,造成内存泄漏。 14 void OnApplicationQuit() 15 { 16 cube = GameObject.Find("Cube0"); 17 plane = GameObject.Find("Plane"); 18 if (cube) 19 { 20 Debug.Log("Cube0 DestroyImmediate"); 21 DestroyImmediate(cube); 22 } 23 if (plane) 24 { 25 Debug.Log("Plane DestroyImmediate"); 26 DestroyImmediate(plane); 27 } 28 } 29 }
NewScene2
1 using UnityEngine; 2 using System.Collections; 3 4 public class NotEditable_ts : MonoBehaviour { 5 public GameObject go; 6 public Transform t; 7 void Start() 8 { 9 //GameObject对象使用HideFlags.NotEditable可以使得GameObject的 10 //所有组件在Inspector面板中都处于不可编辑状态。 11 //GameObject对象被HideFlags.NotEditable标识并不影响其子类的可编辑性。 12 go.hideFlags = HideFlags.NotEditable; 13 GameObject Pl = GameObject.CreatePrimitive(PrimitiveType.Plane); 14 Pl.hideFlags = HideFlags.NotEditable; 15 16 //对于GameObject的某个组件单独使用HideFlags.NotEditable, 17 //只会使得当前组件不可编辑,但GameObject的其他组件扔可编辑。 18 t.hideFlags = HideFlags.NotEditable; 19 Transform tf = Instantiate(t, go.transform.position + new Vector3(2.0f, 0.0f, 0.0f), Quaternion.identity) as Transform; 20 tf.hideFlags = HideFlags.NotEditable; 21 } 22 }
NotEditable
5 Mathf类
1 using UnityEngine; 2 using System.Collections; 3 4 public class Approximately_ts : MonoBehaviour { 5 void Start () { 6 float[] f={0.0f,2.0f,3.0f}; 7 bool b1 = (1 ==101/101) ? true : false; 8 bool b2 = Mathf.Approximately(1.0f, 10.0f/10.0f); 9 Debug.Log("b1:"+b1); 10 Debug.Log("b2:" + b2); 11 Mathf.Min(f); 12 } 13 }
Approximately
1 using UnityEngine; 2 using System.Collections; 3 4 public class Clamp_ts : MonoBehaviour 5 { 6 void Start() 7 { 8 Debug.Log("当value<min时:" + Mathf.Clamp(-1, 0, 10)); 9 Debug.Log("当min<value<max时:" + Mathf.Clamp(3, 0, 10)); 10 Debug.Log("当value>max时:" + Mathf.Clamp(11, 0, 10)); 11 //方法Clamp01的返回值范围为[0,1] 12 Debug.Log("当value<0时:" + Mathf.Clamp01(-0.1f)); 13 Debug.Log("当0<value<1时:" + Mathf.Clamp01(0.5f)); 14 Debug.Log("当value>1时:" + Mathf.Clamp01(1.1f)); 15 } 16 }
Clamp
1 using UnityEngine; 2 using System.Collections; 3 4 public class ClosestPowerOfTwo_ts : MonoBehaviour 5 { 6 void Start() 7 { 8 Debug.Log("11与8最接近,输出值为:" + Mathf.ClosestPowerOfTwo(11)); 9 Debug.Log("12与8和16的差值都为4,输出值为:" + Mathf.ClosestPowerOfTwo(12)); 10 Debug.Log("当value<0时,输出值为:" + Mathf.ClosestPowerOfTwo(-1)); 11 } 12 }
ClosestPowerOfTwo
1 using UnityEngine; 2 using System.Collections; 3 4 public class DegAndRad_ts : MonoBehaviour { 5 void Start () { 6 //从角度到弧度转换常量 7 Debug.Log("Mathf.Deg2Rad:" + Mathf.Deg2Rad); 8 //从弧度到角度转换常量 9 Debug.Log("Mathf.Rad2Deg:" + Mathf.Rad2Deg); 10 } 11 }
DegAndRad
1 using UnityEngine; 2 using System.Collections; 3 4 public class DeltaAngle_ts : MonoBehaviour { 5 void Start () { 6 //1180=360*3+100,即求100和90之间的夹角 7 Debug.Log(Mathf.DeltaAngle(1180, 90)); 8 //-1130=-360*3-50,即求-50和90之间的夹角 9 Debug.Log(Mathf.DeltaAngle(-1130, 90)); 10 //-1200=-360*3-120,即求-120和90之间的夹角 11 Debug.Log(Mathf.DeltaAngle(-1200, 90)); 12 } 13 }
DeltaAngle
1 using UnityEngine; 2 using System.Collections; 3 4 public class Infinity_ts : MonoBehaviour 5 { 6 void Start() 7 { 8 Debug.Log("0:" + Mathf.Infinity); 9 Debug.Log("1:" + Mathf.Infinity / 10000.0f); 10 Debug.Log("2:" + Mathf.Infinity / Mathf.Infinity); 11 } 12 }
Infinity
1 using UnityEngine; 2 using System.Collections; 3 4 public class InverseLerp_ts : MonoBehaviour { 5 void Start () { 6 float f,from,to,v; 7 from=-10.0f; 8 to=30.0f; 9 v=10.0f; 10 f = Mathf.InverseLerp(from,to,v); 11 Debug.Log("当0<f‘<1时:"+f); 12 v = -20.0f; 13 f = Mathf.InverseLerp(from, to, v); 14 Debug.Log("当f‘<0时:" + f); 15 v = 40.0f; 16 f = Mathf.InverseLerp(from, to, v); 17 Debug.Log("当f‘>1时:" + f); 18 } 19 }
InverseLerp
1 using UnityEngine; 2 using System.Collections; 3 4 public class Lerp_ts : MonoBehaviour { 5 float r, g, b; 6 void FixedUpdate () { 7 r = Mathf.Lerp(0.0f,1.0f,Time.time*0.2f); 8 g = Mathf.Lerp(0.0f, 1.0f, -1.0f+Time.time * 0.2f); 9 b = Mathf.Lerp(0.0f, 1.0f, -2.0f+Time.time * 0.2f); 10 light.color = new Color(r, g, b); 11 } 12 }
Lerp
1 using UnityEngine; 2 using System.Collections; 3 4 public class LerpAngle_ts : MonoBehaviour { 5 void Start () { 6 float a, b; 7 a = -50.0f; 8 b = 400.0f; 9 //a‘=360-50=310,b‘=-360+400=40,从而可知c=90, 10 //从a‘沿着逆时针方向可经90度到b‘,故返回值f=a+c*t=-50+90*0.3=-23 11 Debug.Log("test1:"+Mathf.LerpAngle(a,b,0.3f)); 12 13 a = 400.0f; 14 b = -50.0f; 15 //a‘=-360+400=40,b‘=360-50=310,从而可知c=90, 16 //从a‘沿着顺时针方向可经90度到b‘,故返回值f=a-c*t=400-90*0.3=373 17 Debug.Log("test2:" + Mathf.LerpAngle(a, b, 0.3f)); 18 } 19 }
LerpAngle
1 using UnityEngine; 2 using System.Collections; 3 public class MoveTowards_ts : MonoBehaviour 4 { 5 void Start() 6 { 7 float a, b, d; 8 a = 10.0f; 9 b = -10.0f; 10 d = 5.0f; 11 //a>b,且a-d>b,返回值为a-d 12 Debug.Log("Test01:" + Mathf.MoveTowards(a, b, d)); 13 d = 50.0f; 14 //a>b,且a-d<b,返回值为b 15 Debug.Log("Test02:" + Mathf.MoveTowards(a, b, d)); 16 17 a = 10.0f; 18 b = 50.0f; 19 d = 5.0f; 20 //a<b,且a+d<b,返回值为a+d 21 Debug.Log("Test03:" + Mathf.MoveTowards(a, b, d)); 22 d = 50.0f; 23 //a<b,且a+d>b,返回值为b 24 Debug.Log("Test04:" + Mathf.MoveTowards(a, b, d)); 25 } 26 }
MoveTowards
1 using UnityEngine; 2 using System.Collections; 3 4 public class MoveTowardsAngle_ts : MonoBehaviour 5 { 6 float targets = 0.0f; 7 float speed = 40.0f; 8 void Update() 9 { 10 //每帧不超过speed * Time.deltaTime度 11 float angle = Mathf.MoveTowardsAngle(transform.eulerAngles.y, targets, speed * Time.deltaTime); 12 transform.eulerAngles = new Vector3(0, angle, 0); 13 } 14 void OnGUI() 15 { 16 if (GUI.Button(new Rect(10.0f, 10.0f, 200.0f, 45.0f), "顺时针旋转90度")) 17 { 18 targets += 90.0f; 19 } 20 if (GUI.Button(new Rect(10.0f, 60.0f, 200.0f, 45.0f), "逆时针旋转90度")) 21 { 22 targets -= 90.0f; 23 } 24 } 25 }
MoveTowardsAngle
1 using UnityEngine; 2 using System.Collections; 3 4 public class PingPong_ts : MonoBehaviour { 5 void Start () { 6 float f, t, l; 7 t = 11.0f; 8 l = 5.0f; 9 f = Mathf.PingPong(t,l); 10 Debug.Log("l>0,|t|%2l<=l时:"+f); 11 t = 17.0f; 12 l = 5.0f; 13 f = Mathf.PingPong(t, l); 14 Debug.Log("l>0,|t|%2l>l时:" + f); 15 t = 11.0f; 16 l = -5.0f; 17 f = Mathf.PingPong(t, l); 18 Debug.Log("l<0,|t|%2l<=l时:" + f); 19 t = 17.0f; 20 l = -5.0f; 21 f = Mathf.PingPong(t, l); 22 Debug.Log("l<0,|t|%2l>l时:" + f); 23 } 24 }
PingPong
1 using UnityEngine; 2 using System.Collections; 3 4 public class Repeat_ts : MonoBehaviour { 5 void Start () { 6 float f, t, l; 7 t = 12.5f; 8 l = 5.3f; 9 f = Mathf.Repeat(t,l); 10 Debug.Log("t>0,l>0时:"+f); 11 t = -12.5f; 12 l = -5.3f; 13 f = Mathf.Repeat(t, l); 14 Debug.Log("t<0,l<0时:" + f); 15 t = 12.5f; 16 l = -5.3f; 17 f = Mathf.Repeat(t, l); 18 Debug.Log("t>0,l<0时:" + f); 19 t = -12.5f; 20 l = 5.3f; 21 f = Mathf.Repeat(t, l); 22 Debug.Log("t<0,l>0时:" + f); 23 t = -12.5f; 24 l = 0.0f; 25 f = Mathf.Repeat(t, l); 26 Debug.Log("t<0,l==0时:" + f); 27 } 28 }
Repeat
1 using UnityEngine; 2 using System.Collections; 3 4 public class Round_ts : MonoBehaviour 5 { 6 void Start() 7 { 8 //设Round(f)中f=a.b 9 Debug.Log("b<0.5,f>0:" + Mathf.Round(2.49f)); 10 Debug.Log("b<0.5,f<0:" + Mathf.Round(-2.49f)); 11 Debug.Log("b>0.5,f>0:" + Mathf.Round(2.61f)); 12 Debug.Log("b>0.5,f<0:" + Mathf.Round(-2.61f)); 13 Debug.Log("b=0.5,a为偶数,f>0:" + Mathf.Round(6.5f)); 14 Debug.Log("b=0.5,a为偶数,f<0:" + Mathf.Round(-6.5f)); 15 Debug.Log("b=0.5,a为奇数,f>0:" + Mathf.Round(7.5f)); 16 Debug.Log("b=0.5,a为奇数,f<0:" + Mathf.Round(-7.5f)); 17 } 18 }
Round
1 using UnityEngine; 2 using System.Collections; 3 4 public class SmoothDamp_ts : MonoBehaviour 5 { 6 float targets = 110.0f;//目标值 7 float cv1 = 0.0f, cv2 = 0.0f; 8 float maxSpeeds = 50.0f;//每帧最大值 9 float f1 = 10.0f, f2 = 10.0f;//起始值 10 void FixedUpdate() 11 { 12 //maxSpeed取默认值 13 f1 = Mathf.SmoothDamp(f1, targets, ref cv1, 0.5f); 14 Debug.Log("f1:" + f1); 15 Debug.Log("cv1:" + cv1); 16 //maxSpeed取有限值50.0f 17 f2 = Mathf.SmoothDamp(f2, targets, ref cv2, 0.5f, maxSpeeds); 18 Debug.Log("f2:" + f2); 19 Debug.Log("cv2:" + cv2); 20 } 21 }
SmoothDamp
1 using UnityEngine; 2 using System.Collections; 3 4 public class SmoothDampAngle_ts : MonoBehaviour 5 { 6 public Transform targets; 7 float smoothTime = 0.3f; 8 float distance = 5.0f; 9 float yVelocity = 0.0f; 10 void Update() 11 { 12 //返回平滑阻尼角度值 13 float yAngle = Mathf.SmoothDampAngle(transform.eulerAngles.y, targets.eulerAngles.y, ref yVelocity, smoothTime); 14 Vector3 positions = targets.position; 15 //由于使用transform.LookAt,此处计算targets的-z轴方向距离targets为distance, 16 //欧拉角为摄像机绕target的y轴旋转yAngle的坐标位置 17 positions += Quaternion.Euler(0, yAngle, 0) * new Vector3(0, 0, -distance); 18 //向上偏移2个单位 19 transform.position = positions + new Vector3(0.0f, 2.0f, 0.0f); 20 transform.LookAt(targets); 21 } 22 void OnGUI() 23 { 24 if (GUI.Button(new Rect(10.0f, 10.0f, 200.0f, 45.0f), "将targets旋转60度")) 25 { 26 //更改targets的eulerAngles 27 targets.eulerAngles += new Vector3(0.0f, 60.0f, 0.0f); 28 } 29 } 30 }
SmoothDampAngle
1 using UnityEngine; 2 using System.Collections; 3 4 public class SmoothStep_ts : MonoBehaviour { 5 float min = 10.0f; 6 float max = 110.0f; 7 float f1, f2=0.0f; 8 9 void FixedUpdate () { 10 //f1为SmoothStep插值返回值 11 f1 = Mathf.SmoothStep(min,max,Time.time); 12 //计算相邻两帧插值的变化 13 f2 = f1 - f2; 14 Debug.Log("f1:"+f1); 15 Debug.Log("f2:" + f2); 16 f2 = f1; 17 } 18 }
SmoothStep
6 Matrix4x4类
1 using UnityEngine; 2 using System.Collections; 3 4 public class MultiplyVector_ts : MonoBehaviour 5 { 6 public Transform tr; 7 Matrix4x4 mv0 = Matrix4x4.identity; 8 Matrix4x4 mv1 = Matrix4x4.identity; 9 10 void Start() 11 { 12 //分别设置变换矩阵mv0和mv1的位置变换和角度变换都不为0 13 mv0.SetTRS(Vector3.one * 10.0f, Quaternion.Euler(new Vector3(0.0f, 30.0f, 0.0f)), Vector3.one); 14 mv1.SetTRS(Vector3.one * 10.0f, Quaternion.Euler(new Vector3(0.0f, 0.6f, 0.0f)), Vector3.one); 15 } 16 17 void Update() 18 { 19 //用tr来定位变换后的向量 20 tr.position = mv1.MultiplyVector(tr.position); 21 } 22 void OnGUI() 23 { 24 if (GUI.Button(new Rect(10.0f, 10.0f, 120.0f, 45.0f), "方向旋转30度")) 25 { 26 Vector3 v = mv0.MultiplyVector(new Vector3(10.0f, 0.0f, 0.0f)); 27 //打印旋转后的向量,其方向发生了旋转 28 Debug.Log("变换后向量:"+v); 29 //打印旋转后向量的长度, 30 //尽管mv0的位置变换不为0,但变换后向量的长度应与变换前相同 31 Debug.Log("变换后向量模长:" + v.magnitude); 32 } 33 } 34 }
MultiplyVector
1 using UnityEngine; 2 using System.Collections; 3 4 public class OrthoAndPerspective_ts : MonoBehaviour 5 { 6 Matrix4x4 Perspective = Matrix4x4.identity;//透视投影变量 7 Matrix4x4 ortho = Matrix4x4.identity;//正交投影变量 8 //声明变量,用于记录正交视口的左、右、下、上的值 9 float l, r, b, t; 10 void Start() 11 { 12 //设置透视投影矩阵 13 Perspective = Matrix4x4.Perspective(65.0f, 1.5f, 0.1f, 500.0f); 14 t = 10.0f; 15 b = -t; 16 //为防止视图变形需要与 Camera.main.aspect相乘 17 l = b * Camera.main.aspect; 18 r = t * Camera.main.aspect; 19 //设置正交投影矩阵 20 ortho = Matrix4x4.Ortho(l, r, b, t, 0.1f, 100.0f); 21 } 22 23 void OnGUI() 24 { 25 //使用默认正交投影 26 if (GUI.Button(new Rect(10.0f, 8.0f, 150.0f, 20.0f), "Reset Ortho")) 27 { 28 Camera.main.orthographic = true; 29 Camera.main.ResetProjectionMatrix(); 30 Camera.main.orthographicSize = 5.1f; 31 } 32 //使用自定义正交投影 33 if (GUI.Button(new Rect(10.0f, 38.0f, 150.0f, 20.0f), "use Ortho")) 34 { 35 ortho = Matrix4x4.Ortho(l, r, b, t, 0.1f, 100.0f); 36 Camera.main.orthographic = true; 37 Camera.main.ResetProjectionMatrix(); 38 Camera.main.projectionMatrix = ortho; 39 Camera.main.orthographicSize = 5.1f; 40 } 41 //使用自定义透视投影 42 if (GUI.Button(new Rect(10.0f, 68.0f, 150.0f, 20.0f), "use Perspective")) 43 { 44 Camera.main.orthographic = false; 45 Camera.main.projectionMatrix = Perspective; 46 } 47 //恢复系统默认透视投影 48 if (GUI.Button(new Rect(10.0f, 98.0f, 150.0f, 20.0f), "Reset Perspective")) 49 { 50 Camera.main.orthographic = false; 51 Camera.main.ResetProjectionMatrix(); 52 } 53 } 54 }
OrthoAndPerspective
1 using UnityEngine; 2 using System.Collections; 3 4 public class SetTRS_ts : MonoBehaviour 5 { 6 Vector3 v1 = Vector3.one; 7 Vector3 v2 = Vector3.zero; 8 9 void Start() 10 { 11 Matrix4x4 m1 = Matrix4x4.identity; 12 //Position沿Y轴增加5个单位,绕Y轴旋转45度,放缩2倍 13 m1.SetTRS(Vector3.up * 5, Quaternion.Euler(Vector3.up * 45.0f), Vector3.one * 2.0f); 14 //也可以使用如下静态方法设置m1变换 15 //m1 = Matrix4x4.TRS(Vector3.up * 5, Quaternion.Euler(Vector3.up * 45.0f), Vector3.one * 2.0f); 16 v2 = m1.MultiplyPoint3x4(v1); 17 Debug.Log("v1的值:" + v1); 18 Debug.Log("v2的值:" + v2); 19 } 20 21 void FixedUpdate() 22 { 23 Debug.DrawLine(Vector3.zero, v1, Color.green); 24 Debug.DrawLine(Vector3.zero, v2, Color.red); 25 } 26 }
SetTRS
7 Object类
1 using UnityEngine; 2 using System.Collections; 3 4 public class Destroy_ts : MonoBehaviour { 5 public GameObject GO,Cube; 6 void Start () { 7 //5秒后销毁GO对象的Rigidbody组件 8 Destroy(GO.rigidbody,5.0f); 9 //7秒后销毁GO对象中的Destroy_ts脚本 10 Destroy(GO.GetComponent<Destroy_ts>(),7.0f); 11 //10秒后销毁Cube对象,同时Cube对象的所有组件及子类将一并销毁 12 Destroy(Cube, 10.0f); 13 } 14 }
Destroy
1 using UnityEngine; 2 using System.Collections; 3 4 public class DontDestoryOnLoad_ts : MonoBehaviour 5 { 6 public GameObject g1, g2; 7 public Renderer re1, re2; 8 void Start() 9 { 10 //g1指向一个顶层父物体对象,在导入新Scene时g1被保存 11 DontDestroyOnLoad(g1); 12 //g2指向一个子类对象,在导入新Scene时会发现g2没有被保存 13 DontDestroyOnLoad(g2); 14 //re1指向一个顶层父物体的Renderer组件,在导入新Scene时re1被保存 15 DontDestroyOnLoad(re1); 16 //re2指向一个子类对象的renderer组件,在导入新Scene时会发现re2指向的对象及组件没有被保存 17 DontDestroyOnLoad(re2); 18 Application.LoadLevel("FindObjectsOfType_unity"); 19 } 20 }
DontDestoryOnLoad
1 using UnityEngine; 2 using System.Collections; 3 4 public class FindObjectOfType_ts : MonoBehaviour { 5 void Start () { 6 GameObject[] gos = FindObjectsOfType(typeof(GameObject)) as GameObject[]; 7 foreach(GameObject go in gos){ 8 //1.5秒后销毁除摄像机外的所有GameObject 9 if (go.name != "Main Camera") 10 { 11 Destroy(go, 1.5f); 12 } 13 } 14 15 Rigidbody[] rbs = FindObjectsOfType(typeof(Rigidbody))as Rigidbody[]; 16 foreach(Rigidbody rb in rbs){ 17 //启用除球体外的所有刚体的重力感应 18 if(rb.name!="Sphere"){ 19 rb.useGravity = true; 20 } 21 } 22 } 23 }
FindObjectOfType
1 using UnityEngine; 2 using System.Collections; 3 4 public class GetInstanceID_ts : MonoBehaviour { 5 void Start () { 6 Debug.Log("gameObject的ID:"+gameObject.GetInstanceID()); 7 Debug.Log("transform的ID:"+transform.GetInstanceID()); 8 9 GameObject g1, g2; 10 //从GameObject创建一个对象 11 g1=GameObject.CreatePrimitive(PrimitiveType.Cube); 12 //克隆对象 13 g2=Instantiate(g1,Vector3.zero,Quaternion.identity)as GameObject; 14 15 Debug.Log("GameObject g1的ID:"+g1.GetInstanceID()); 16 Debug.Log("Transform g1的ID:"+g1.transform.GetInstanceID()); 17 18 Debug.Log("GameObject g2的ID:" + g2.GetInstanceID()); 19 Debug.Log("Transform g2的ID:" + g2.transform.GetInstanceID()); 20 } 21 }
GetInstanceID
1 using UnityEngine; 2 using System.Collections; 3 4 public class Instantiate_ts : MonoBehaviour { 5 public GameObject A; 6 public Transform B; 7 public Rigidbody C; 8 void Start () { 9 Object g1 = Instantiate(A,Vector3.zero,Quaternion.identity) as Object; 10 Debug.Log("克隆一个Object对象g1:"+g1); 11 GameObject g2 = Instantiate(A, Vector3.zero, Quaternion.identity) as GameObject; 12 Debug.Log("克隆一个GameObject对象g2:" + g2); 13 Transform t1 = Instantiate(B, Vector3.zero, Quaternion.identity) as Transform; 14 Debug.Log("克隆一个Transform对象t1:" + t1); 15 Rigidbody r1 = Instantiate(C, Vector3.zero, Quaternion.identity) as Rigidbody; 16 Debug.Log("克隆一个Rigidbody对象r1:" + r1); 17 } 18 }
Instantiate
8 Quaternion类
1 using UnityEngine; 2 using System.Collections; 3 4 public class Angle_ts : MonoBehaviour { 5 void Start() 6 { 7 Quaternion q1 = Quaternion.identity; 8 Quaternion q2 = Quaternion.identity; 9 q1.eulerAngles = new Vector3(10.0f, 20.0f, 30.0f); 10 float f1 = Quaternion.Angle(q1,q2); 11 float f2 = 0.0f; 12 Vector3 v1 = Vector3.zero; 13 q1.ToAngleAxis(out f2, out v1); 14 15 Debug.Log("f1:" + f1); 16 Debug.Log("f2:" + f2); 17 Debug.Log("q1的欧拉角:" + q1.eulerAngles + " q1的rotation:" + q1); 18 Debug.Log("q2的欧拉角:" + q2.eulerAngles + " q2的rotation:" + q2); 19 } 20 }
Angle
1 using UnityEngine; 2 using System.Collections; 3 4 public class Dot_ts : MonoBehaviour { 5 public Transform A, B; 6 Quaternion q1=Quaternion.identity; 7 Quaternion q2=Quaternion.identity; 8 float f; 9 10 void Start () { 11 A.eulerAngles = new Vector3(0.0f,40.0f,0.0f); 12 //B比A绕Y轴多转360度 13 B.eulerAngles = new Vector3(0.0f, 360.0f+40.0f, 0.0f); 14 q1 = A.rotation; 15 q2 = B.rotation; 16 f = Quaternion.Dot(q1,q2); 17 Debug.Log("q1的rotation:"+q1); 18 Debug.Log("q2的rotation:" + q2); 19 Debug.Log("q1的欧拉角:" + q1.eulerAngles); 20 Debug.Log("q2的欧拉角:" + q2.eulerAngles); 21 Debug.Log("Dot(q1,q2):"+f); 22 } 23 }
Dot
1 using UnityEngine; 2 using System.Collections; 3 4 public class Euler_ts : MonoBehaviour 5 { 6 //记录欧拉角,单位为角度,可以在Inspector面板中设置 7 public float ex, ey, ez; 8 //用于记录计算结果 9 float qx, qy, qz, qw; 10 float PIover180 = 0.0174532925f;//常量 11 Quaternion Q = Quaternion.identity; 12 void OnGUI() 13 { 14 if (GUI.Button(new Rect(10.0f, 10.0f, 100.0f, 45.0f), "计算")) 15 { 16 Debug.Log("欧拉角:" + " ex:" + ex + " ey:" + ey + " ez:" + ez); 17 //调用方法计算 18 Q = Quaternion.Euler(ex, ey, ez); 19 Debug.Log("Q.x:" + Q.x + " Q.y:" + Q.y + " Q.z:" + Q.z + " Q.w:" + Q.w); 20 //测试算法 21 ex = ex * PIover180 / 2.0f; 22 ey = ey * PIover180 / 2.0f; 23 ez = ez * PIover180 / 2.0f; 24 qx = Mathf.Sin(ex) * Mathf.Cos(ey) * Mathf.Cos(ez) + Mathf.Cos(ex) * Mathf.Sin(ey) * Mathf.Sin(ez); 25 qy = Mathf.Cos(ex) * Mathf.Sin(ey) * Mathf.Cos(ez) - Mathf.Sin(ex) * Mathf.Cos(ey) * Mathf.Sin(ez); 26 qz = Mathf.Cos(ex) * Mathf.Cos(ey) * Mathf.Sin(ez) - Mathf.Sin(ex) * Mathf.Sin(ey) * Mathf.Cos(ez); 27 qw = Mathf.Cos(ex) * Mathf.Cos(ey) * Mathf.Cos(ez) + Mathf.Sin(ex) * Mathf.Sin(ey) * Mathf.Sin(ez); 28 Debug.Log(" qx:" + qx + " qy:" + qy + " qz:" + qz + " qw:" + qw); 29 } 30 } 31 }
Euler
1 using UnityEngine; 2 using System.Collections; 3 4 public class EulerAngle_ts : MonoBehaviour 5 { 6 public Transform A, B; 7 Quaternion rotations=Quaternion.identity; 8 Vector3 eulerAngle = Vector3.zero; 9 float speed = 10.0f; 10 11 void Update() 12 { 13 //第一种方式:将Quaternion赋值给transform的rotation 14 rotations.eulerAngles = new Vector3(0.0f, speed * Time.time, 0.0f); 15 A.rotation = rotations; 16 //第二种方式:将三维向量代表的欧拉角直接赋值给transform的eulerAngles 17 eulerAngle = new Vector3(0.0f, speed * Time.time, 0.0f); 18 B.eulerAngles = eulerAngle; 19 } 20 }
EulerAngle
1 using UnityEngine; 2 using System.Collections; 3 4 public class FromToRotation_ts : MonoBehaviour 5 { 6 public Transform A, B, C, D; 7 Quaternion q1 = Quaternion.identity; 8 9 void Update() 10 { 11 //使用实例方法 12 //不可直接使用C.rotation.SetFromToRotation(A.position,B.position); 13 q1.SetFromToRotation(A.position, B.position); 14 C.rotation = q1; 15 //使用类方法 16 D.rotation = Quaternion.FromToRotation(A.position, B.position); 17 //在Scene视图中绘制直线 18 Debug.DrawLine(Vector3.zero, A.position, Color.white); 19 Debug.DrawLine(Vector3.zero, B.position, Color.white); 20 Debug.DrawLine(C.position, C.position + new Vector3(0.0f, 1.0f, 0.0f), Color.white); 21 Debug.DrawLine(C.position, C.TransformPoint(Vector3.up * 1.5f), Color.white); 22 Debug.DrawLine(D.position, D.position + new Vector3(0.0f, 1.0f, 0.0f), Color.white); 23 Debug.DrawLine(D.position, D.TransformPoint(Vector3.up * 1.5f), Color.white); 24 } 25 }
FromToRotation
1 using UnityEngine; 2 using System.Collections; 3 4 public class Inverse_ts : MonoBehaviour 5 { 6 public Transform A, B; 7 void Start() 8 { 9 Quaternion q1 = Quaternion.identity; 10 Quaternion q2 = Quaternion.identity; 11 q1.eulerAngles = new Vector3(10.0f, 20.0f, 30.0f); 12 q2 = Quaternion.Inverse(q1); 13 14 A.rotation = q1; 15 B.rotation = q2; 16 17 Debug.Log("q1的欧拉角:" + q1.eulerAngles + " q1的rotation:" + q1); 18 Debug.Log("q2的欧拉角:" + q2.eulerAngles + " q2的rotation:" + q2); 19 } 20 }
Inverse
1 using UnityEngine; 2 using System.Collections; 3 4 public class LookRotation_ts : MonoBehaviour 5 { 6 public Transform A, B, C, D; 7 Quaternion q1 = Quaternion.identity; 8 9 void Update() 10 { 11 //使用实例方法 12 //不可直接使用C.rotation.SetLookRotation(A.position,B.position); 13 q1.SetLookRotation(A.position, B.position); 14 C.rotation = q1; 15 //使用类方法 16 D.rotation = Quaternion.LookRotation(A.position, B.position); 17 //绘制直线,请在Scene视图中查看 18 Debug.DrawLine(Vector3.zero, A.position, Color.white); 19 Debug.DrawLine(Vector3.zero, B.position, Color.white); 20 Debug.DrawLine(C.position, C.TransformPoint(Vector3.up * 2.5f), Color.white); 21 Debug.DrawLine(C.position, C.TransformPoint(Vector3.forward * 2.5f), Color.white); 22 Debug.DrawLine(D.position, D.TransformPoint(Vector3.up * 2.5f), Color.white); 23 Debug.DrawLine(D.position, D.TransformPoint(Vector3.forward * 2.5f), Color.white); 24 } 25 }
LookRotation
1 using UnityEngine; 2 using System.Collections; 3 4 public class QxQ_ts : MonoBehaviour { 5 public Transform A, B; 6 7 void Start () { 8 //设置A的欧拉角 9 //试着更改各个分量查看B的不同旋转状态 10 A.eulerAngles = new Vector3(1.0f,1.5f,2.0f); 11 } 12 13 void Update () { 14 B.rotation *= A.rotation; 15 //输出B的欧拉角,注意观察B的欧拉角变化 16 Debug.Log(B.eulerAngles); 17 } 18 }
QxQ
1 using UnityEngine; 2 using System.Collections; 3 4 public class QxV_ts : MonoBehaviour 5 { 6 public Transform A; 7 float speed = 0.1f; 8 //初始化A的position和eulerAngles 9 void Start() 10 { 11 A.position = Vector3.zero; 12 A.eulerAngles = new Vector3(0.0f, 45.0f, 0.0f); 13 } 14 15 void Update() 16 { 17 //沿着A的自身坐标系的forward方向每帧前进speed距离 18 A.position += A.rotation * (Vector3.forward * speed); 19 Debug.Log(A.position); 20 } 21 }
QxV
1 using UnityEngine; 2 using System.Collections; 3 4 public class RotateTowards_ts : MonoBehaviour { 5 public Transform A, B, C; 6 float speed = 10.0f; 7 8 void Update() 9 { 10 C.rotation = Quaternion.RotateTowards(A.rotation, B.rotation, Time.time * speed-40.0f); 11 Debug.Log("C与A的欧拉角的差值:" + (C.eulerAngles-A.eulerAngles) + " maxDegreesDelta:" + (Time.time * speed - 40.0f)); 12 } 13 }
RotateTowards
1 using UnityEngine; 2 using System.Collections; 3 4 public class SetFromToRotation_ts : MonoBehaviour { 5 public Transform A, B, C; 6 Quaternion q1 = Quaternion.identity; 7 8 void Update () { 9 //不可直接使用C.rotation.SetFromToRotation(A.position,B.position); 10 q1.SetFromToRotation(A.position,B.position); 11 C.rotation = q1; 12 13 Debug.DrawLine(Vector3.zero,A.position,Color.red); 14 Debug.DrawLine(Vector3.zero, B.position, Color.green); 15 Debug.DrawLine(C.position, C.position+new Vector3(0.0f,1.0f,0.0f), Color.black); 16 Debug.DrawLine(C.position, C.TransformPoint(Vector3.up*1.5f), Color.yellow); 17 } 18 }
SetFromToRotation
1 using UnityEngine; 2 using System.Collections; 3 4 public class SetLookRotation_ts : MonoBehaviour 5 { 6 public Transform A, B, C; 7 Quaternion q1 = Quaternion.identity; 8 9 void Update() 10 { 11 //不可直接使用C.rotation.SetLookRotation(A.position,B.position); 12 q1.SetLookRotation(A.position, B.position); 13 C.rotation = q1; 14 //分别绘制A、B和C.right的朝向线 15 //请在Scene视图中查看 16 Debug.DrawLine(Vector3.zero, A.position, Color.red); 17 Debug.DrawLine(Vector3.zero, B.position, Color.green); 18 Debug.DrawLine(C.position, C.TransformPoint(Vector3.right * 2.5f), Color.yellow); 19 Debug.DrawLine(C.position, C.TransformPoint(Vector3.forward * 2.5f), Color.black); 20 //分别打印C.right与A、B的夹角 21 Debug.Log("C.right与A的夹角:" + Vector3.Angle(C.right, A.position)); 22 Debug.Log("C.right与B的夹角:" + Vector3.Angle(C.right, B.position)); 23 //C.up与B的夹角 24 Debug.Log("C.up与B的夹角:" + Vector3.Angle(C.up, B.position)); 25 } 26 }
SetLookRotation
1 using UnityEngine; 2 using System.Collections; 3 4 public class Slerp_ts : MonoBehaviour 5 { 6 public Transform A, B, C, D; 7 float speed = 0.2f; 8 //分别演示方法Slerp和Lerp的使用 9 void Update() 10 { 11 C.rotation = Quaternion.Slerp(A.rotation, B.rotation, Time.time * speed); 12 D.rotation = Quaternion.Lerp(A.rotation, B.rotation, Time.time * speed); 13 } 14 }
Slerp
1 using UnityEngine; 2 using System.Collections; 3 4 public class ToAngleAxis_ts : MonoBehaviour 5 { 6 public Transform A, B; 7 float angle; 8 Vector3 axis = Vector3.zero; 9 10 void Update() 11 { 12 //使用ToAngleAxis获取A的Rotation的旋转轴和角度 13 A.rotation.ToAngleAxis(out angle, out axis); 14 //使用AngleAxis设置B的rotation,使得B的rotation状态的和A相同 15 //可以在程序运行时修改A的rotation查看B的状态 16 B.rotation = Quaternion.AngleAxis(angle, axis); 17 } 18 }
ToAngleAxis
9 Random类
1 using UnityEngine; 2 using System.Collections; 3 4 public class insideUnitCircle_ts : MonoBehaviour 5 { 6 public GameObject go; 7 8 void Start() 9 { 10 //每隔0.4秒执行一次use_rotationUniform方法 11 InvokeRepeating("use_rotationUniform", 1.0f, 0.4f); 12 } 13 14 void use_rotationUniform() 15 { 16 //在半径为5的圆内随机位置实例化一个GameObject对象 17 //Vector2实例转为Vector3时,z轴分量默认为0 18 Instantiate(go, Random.insideUnitCircle * 5.0f, Quaternion.identity); 19 //在半径为5的球内随机位置实例化一个GameObject对象 20 Instantiate(go, Vector3.forward * 15.0f + 5.0f * Random.insideUnitSphere, Quaternion.identity); 21 //在半径为5的球表面随机位置实例化一个GameObject对象 22 Instantiate(go, Vector3.forward * 30.0f + 5.0f * Random.onUnitSphere, Quaternion.identity); 23 } 24 }
insideUnitCircle
1 using UnityEngine; 2 using System.Collections; 3 4 public class rotationUniform_ts : MonoBehaviour 5 { 6 public GameObject go; 7 GameObject cb, sp; 8 GameObject cb1, sp1; 9 10 void Start() 11 { 12 //分别获取cb、sp、cb1和sp1对象 13 cb = GameObject.Find("Cube"); 14 sp = GameObject.Find("Cube/Sphere"); 15 cb1 = GameObject.Find("Cube1"); 16 sp1 = GameObject.Find("Cube1/Sphere1"); 17 //每隔0.4秒执行一次use_rotationUniform方法 18 InvokeRepeating("use_rotationUniform", 1.0f, 0.4f); 19 } 20 21 void use_rotationUniform() 22 { 23 //使用rotationUniform产生符合均匀分布特征的rotation 24 cb.transform.rotation = Random.rotationUniform; 25 //使用rotation产生一个随机rotation 26 cb1.transform.rotation = Random.rotation; 27 //分别在sp和sp1的位置实例化一个GameObject对象 28 Instantiate(go, sp.transform.position, Quaternion.identity); 29 Instantiate(go, sp1.transform.position, Quaternion.identity); 30 } 31 }
rotationUniform
1 using UnityEngine; 2 using System.Collections; 3 4 public class Seed_ts : MonoBehaviour 5 { 6 void Start() 7 { 8 //设置随机数的种子 9 //不同的种子产生不同的随机数序列 10 //对于相同的种子,在程序每次启动时其序列是相同的 11 Random.seed = 1; 12 } 13 void Update() 14 { 15 Debug.Log(Random.value); 16 } 17 }
Seed
10 Rigidbody类
11 Time类
12 Transform类
13 Vector2类
14 Vector3类