这里只列举了一部分,更多的看Scripting API数组
using System.Collections; using System.Collections.Generic; using UnityEngine; public class API02Time : MonoBehaviour { // Use this for initialization void Start () { Debug.Log("Time.deltaTime:" + Time.deltaTime);//完成最后一帧(只读)所需的时间(秒) Debug.Log("Time.fixedDeltaTime:" + Time.fixedDeltaTime);//执行物理和其余固定帧速率更新(如MonoBehaviour的FixedUpdate)的间隔,以秒为单位。 Debug.Log("Time.fixedTime:" + Time.fixedTime);//最新的FixedUpdate启动时间(只读)。这是自游戏开始以来的时间单位为秒。 Debug.Log("Time.frameCount:" + Time.frameCount);//已经过的帧总数(只读)。 Debug.Log("Time.realtimeSinceStartup:" + Time.realtimeSinceStartup);//游戏开始后以秒为单位的实时时间(只读)。 Debug.Log("Time.smoothDeltaTime:" + Time.smoothDeltaTime);//平滑的时间(只读)。 Debug.Log("Time.time:" + Time.time);//此帧开头的时间(仅读)。这是自游戏开始以来的时间单位为秒。 Debug.Log("Time.timeScale:" + Time.timeScale);//时间流逝的尺度。这能够用于慢动做效果。 Debug.Log("Time.timeSinceLevelLoad:" + Time.timeSinceLevelLoad);//此帧已开始的时间(仅读)。这是自加载上一个级别以来的秒时间。 Debug.Log("Time.unscaledTime:" + Time.unscaledTime);//此帧的时间尺度无关时间(只读)。这是自游戏开始以来的时间单位为秒。 float time0 = Time.realtimeSinceStartup; for(int i = 0; i < 1000; i++) { Method(); } float time1 = Time.realtimeSinceStartup; Debug.Log("总共耗时:" + (time1 - time0)); } void Method() { int i = 2; i *= 2; i *= 2; } }
建立物体的3种方法:
1 构造方法
2 Instantiate 能够根据prefab 或者 另一个游戏物体克隆
3 CreatePrimitive 建立原始的几何体dom
using System.Collections; using System.Collections.Generic; using UnityEngine; public class API03GameObject : MonoBehaviour { void Start () { // 1 第一种,构造方法 GameObject go = new GameObject("Cube"); // 2 第二种 //根据prefab //根据另一个游戏物体 GameObject.Instantiate(go); // 3 第三种 建立原始的几何体 GameObject.CreatePrimitive(PrimitiveType.Plane); GameObject go2 = GameObject.CreatePrimitive(PrimitiveType.Cube); } }
AddComponent:添加组件,能够添加系统组件或者自定义的脚本异步
using System.Collections; using System.Collections.Generic; using UnityEngine; public class API03GameObject : MonoBehaviour { void Start () { GameObject go = new GameObject("Cube"); go.AddComponent<Rigidbody>();//添加系统组件 go.AddComponent<API01EventFunction>();//添加自定义脚本 } }
禁用和启用游戏物体:
activeSelf:自身的激活状态
activeInHierarchy:在Hierarchy的激活状态
SetActive(bool):设置激活状态ide
using System.Collections; using System.Collections.Generic; using UnityEngine; public class API03GameObject : MonoBehaviour { void Start () { GameObject go = new GameObject("Cube"); Debug.Log(go.activeInHierarchy); go.SetActive(false); Debug.Log(go.activeInHierarchy); } }
游戏物体查找:函数
Find:按名称查找GameObject并返回它
FindObjectOfType:根据类型返回类型的第一个活动加载对象
FindObjectsOfType:根据类型返回类型的全部活动加载对象的列表
FindWithTag:根据标签返回一个活动的GameObject标记。若是没有找到GameObject,则返回NULL。
FindGameObjectsWithTag:根据标签返回活动游戏对象标记的列表。若是没有找到GameObject,则返回空数组。
transform.Findui
GameObject.Find和transform.Find的区别:
public static GameObject Find(string name);
适用于整个游戏场景中名字为name的全部处于活跃状态的游戏对象。若是在场景中有多个同名的活跃的游戏对象,在屡次运行的时候,结果是固定的。this
public Transform Find(string name);
适用于查找游戏对象子对象名字为name的游戏对象,无论该游戏对象是不是激活状态,均可以找到。只能是游戏对象直接的子游戏对象。url
using System.Collections; using System.Collections.Generic; using UnityEngine; public class API03GameObject : MonoBehaviour { void Start () { Light light = FindObjectOfType<Light>(); light.enabled = false; Transform[] ts = FindObjectsOfType<Transform>(); foreach (Transform t in ts) { Debug.Log(t); } GameObject mainCamera = GameObject.Find("Main Camera"); GameObject[] gos = GameObject.FindGameObjectsWithTag("MainCamera"); GameObject gos1 = GameObject.FindGameObjectWithTag("Finish"); } }
BroacastMessage:发送消息,向下传递(子)
SendMessage:发送消息,须要目标target
SendMessageUpwards:发送消息,向上传递(父)pwa
using System.Collections; using System.Collections.Generic; using UnityEngine; public class API04Message : MonoBehaviour { private GameObject son; void Start () { son = GameObject.Find("Son"); // 向下传递消息 // SendMessageOptions.DontRequireReceiver表示能够没有接收者 //BroadcastMessage("Test", null, SendMessageOptions.DontRequireReceiver); // 广播消息 son.SendMessage("Test", null, SendMessageOptions.DontRequireReceiver); // 向上传递消息 //SendMessageUpwards("Test", null, SendMessageOptions.DontRequireReceiver); } }
GetComponet(s):查找单个(全部)游戏组件
GetComponet(s)InChildren:查找children中单个(全部)游戏组件
GetComponet(s)InParent:查找parent中单个(全部)游戏组件插件
注意:若是是查找单个,若找到第一个后,直接返回,再也不向后查找
using System.Collections; using System.Collections.Generic; using UnityEngine; public class API05GetComponent : MonoBehaviour { void Start () { Light light = this.transform.GetComponent<Light>(); light.color = Color.red; } }
Invoke:调用函数
InvokeRepeating:重复调用
CancelInvoke:取消调用
IsInvoking:函数是否被调用
using System.Collections; using System.Collections.Generic; using UnityEngine; public class API06Invoke : MonoBehaviour { void Start () { // Invoke(函数名,延迟时间) //Invoke("Attack", 3); // InvokeRepeating(函数名,延迟时间,调用间隔) InvokeRepeating("Attack", 4, 2); // CancelInvoke(函数名) //CancelInvoke("Attack"); } void Update() { // 判断是否正在循环执行该函数 bool res = IsInvoking("Attack"); print(res); } void Attack() { Debug.Log("开始攻击"); } }
定义使用IEnumerator
返回使用yield
调用使用StartCoroutine
关闭使用StopCoroutine
StopAllCoroutine
延迟几秒:yield return new WaitForSeconds(time);
using System.Collections; using System.Collections.Generic; using UnityEngine; public class API08Coroutine : MonoBehaviour { public GameObject cube; private IEnumerator ie; void Start() { print("协程开启前"); StartCoroutine(ChangeColor()); //协程方法开启后,会继续运行下面的代码,不会等协程方法运行结束才继续执行 print("协程开启后"); } void Update() { if (Input.GetKeyDown(KeyCode.Space)) { ie = Fade(); StartCoroutine(ie); } if (Input.GetKeyDown(KeyCode.S)) { StopCoroutine(ie); } } IEnumerator Fade() { for (; ; ) { Color color = cube.GetComponent<MeshRenderer>().material.color; Color newColor = Color.Lerp(color, Color.red, 0.02f); cube.GetComponent<MeshRenderer>().material.color = newColor; yield return new WaitForSeconds(0.02f); if (Mathf.Abs(Color.red.g - newColor.g) <= 0.01f) { break; } } } IEnumerator ChangeColor() { print("hahaColor"); yield return new WaitForSeconds(3); cube.GetComponent<MeshRenderer>().material.color = Color.blue; print("hahaColor"); yield return null; } }
OnMouseDown:鼠标按下
OnMouseUp:鼠标抬起
OnMouseDrag:鼠标拖动
OnMouseEnter:鼠标移上
OnMouseExit:鼠标移开
OnMouseOver:鼠标在物体上
OnMouseUpAsButton:鼠标移开时触发,且移上和移开在同一物体上才会触发
using System.Collections; using System.Collections.Generic; using UnityEngine; public class API08OnMouseEventFunction : MonoBehaviour { void OnMouseDown() { print("Down"+gameObject); } void OnMouseUp() { print("up" + gameObject); } void OnMouseDrag() { print("Drag" + gameObject); } void OnMouseEnter() { print("Enter"); } void OnMouseExit() { print("Exit"); } void OnMouseOver() { print("Over"); } void OnMouseUpAsButton() { print("Button" + gameObject); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class API09Mathf : MonoBehaviour { public Transform cube; public int a = 8; public int b = 20; public float t = 0; public float speed = 3; void Start() { /* 静态变量 */ // 度数--->弧度 print(Mathf.Deg2Rad); // 弧度--->度数 print(Mathf.Rad2Deg); // 无穷大 print(Mathf.Infinity); // 无穷小 print(Mathf.NegativeInfinity); // 无穷小,接近0 print(Mathf.Epsilon); // π print(Mathf.PI); /* 静态方法 */ // 向下取整 Debug.Log(Mathf.Floor(10.2F)); Debug.Log(Mathf.Floor(-10.2F)); // 取得离value最近的2的某某次方数 print(Mathf.ClosestPowerOfTwo(2));//2 print(Mathf.ClosestPowerOfTwo(3));//4 print(Mathf.ClosestPowerOfTwo(4));//4 print(Mathf.ClosestPowerOfTwo(5));//4 print(Mathf.ClosestPowerOfTwo(6));//8 print(Mathf.ClosestPowerOfTwo(30));//32 // 最大最小值 print(Mathf.Max(1, 2, 5, 3, 10));//10 print(Mathf.Min(1, 2, 5, 3, 10));//1 // a的b次方 print(Mathf.Pow(4, 3));//64 // 开平方根 print(Mathf.Sqrt(3));//1.6 cube.position = new Vector3(0, 0, 0); } void Update() { // Clamp(value,min,max):把一个值限定在一个范围以内 cube.position = new Vector3(Mathf.Clamp(Time.time, 1.0F, 3.0F), 0, 0); Debug.Log(Mathf.Clamp(Time.time, 1.0F, 3.0F)); // Lerp(a,b,t):插值运算,从a到b的距离s,每次运算到这个距离的t*s // Lerp(0,10,0.1)表示从0到10,每次运动剩余量的0.1,第一次运动到1,第二次运动到0.9... //print(Mathf.Lerp(a, b, t)); float x = cube.position.x; //float newX = Mathf.Lerp(x, 10, Time.deltaTime); // MoveTowards(a,b,value):移动,从a到b,每次移动value float newX = Mathf.MoveTowards(x, 10, Time.deltaTime*speed); cube.position = new Vector3(newX, 0, 0); // PingPong(speed,distance):像乒乓同样来回运动,速度为speed,范围为0到distance print(Mathf.PingPong(t, 20)); cube.position = new Vector3(5+Mathf.PingPong(Time.time*speed, 5), 0, 0); } }
静态方法:
GetKeyDown(KeyCode):按键按下
GetKey(KeyCode):按键按下没松开
GetKeyUp(KeyCode):按键松开
KeyCode:键盘按键码,能够是键码(KeyCode.UP),也能够是名字("up")
GetMouseButtonDown(0 or 1 or 2):鼠标按下
GetMouseButton(0 or 1 or 2):鼠标按下没松开
GetMouseButtonUp(0 or 1 or 2):鼠标松开
0:左键 1:右键 2:中键
GetButtonDown(Axis):虚拟按键按下
GetButton(Axis):虚拟按键按下没松开
GetButtonUp(Axis):虚拟按键松开
Axis:虚拟轴名字
GetAxis(Axis):返回值为float,上面的是返回bool
cube.Translate(Vector3.right * Time.deltaTime * Input.GetAxis("Horizontal")*10);
静态变量:
anyKeyDown:任何键按下(鼠标+键盘)
mousePosition:鼠标位置
using System.Collections; using System.Collections.Generic; using UnityEngine; public class API10Input : MonoBehaviour { void Update() { if (Input.GetKeyDown(KeyCode.Space)) { print("KeyDOwn"); } if (Input.GetKeyUp(KeyCode.Space)) { print("KeyUp"); } if (Input.GetKey(KeyCode.Space)) { print("Key"); } if (Input.GetMouseButton(0)) Debug.Log("Pressed left click."); if (Input.GetMouseButtonDown(0)) Debug.Log("Pressed left click."); if (Input.GetButtonDown("Horizontal")) { print("Horizontal Down"); } // GetAxis:这样使用有加速减速效果,若是是速度改变等状况不会突变 //this.transform.Translate(Vector3.right * Time.deltaTime * Input.GetAxis("Horizontal") * 10); //GetAxisRaw:没有加速减速效果,速度改变等状况直接突变 this.transform.Translate(Vector3.right * Time.deltaTime * Input.GetAxisRaw("Horizontal") * 10); if (Input.anyKeyDown) { print("any key down"); } print(Input.mousePosition); } }
Input输入类之触摸事件: 推荐使用Easytouch插件
Input.touches.Length:触摸点个数
Input.touches[i]:获取第i个触摸点信息
touch1.position:触摸点位置
touch1.phase:触摸点状态
using System.Collections; using System.Collections.Generic; using UnityEngine; public class TouchTest : MonoBehaviour { // Update is called once per frame void Update () { //Debug.Log(Input.touches.Length); if (Input.touches.Length > 0) { Touch touch1 = Input.touches[0]; //touch1.position; TouchPhase phase = touch1.phase; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class API11Vector2 : MonoBehaviour { void Start() { /* 静态变量 */ // up,down,left,right,one,zero:分别表示点(0,1)(0,-1)(-1,0)(1,0)(1,1)(0,0) print(Vector2.down); print(Vector2.up); print(Vector2.left); print(Vector2.right); print(Vector2.one); print(Vector2.zero); // x,y:x坐标,y坐标(若是有一个向量Vector2 vec,也能够使用vec[0]和vec[1]来表示x和y坐标) Vector2 vec1 = new Vector2(3, 4); Debug.Log("x:" + vec1.x); Debug.Log("x:" + vec1[0]); Debug.Log("y:" + vec1.y); Debug.Log("x:" + vec1[1]); // magnitude:向量的长度 Debug.Log(vec1.magnitude); // sqrMagnitude:向量的长度的平方(即上面的没开根号前,若是只是用来比较的话,不须要开根号) Debug.Log(vec1.sqrMagnitude); // normalized:返回该向量的单位化向量(若是有一贯量,返回一个新向量,方向不变,但长度变为1) Debug.Log(vec1.normalized); // normalize:返回自身,自身被单位化 vec1.Normalize(); Debug.Log("x:" + vec1.x); Debug.Log("y:" + vec1.y); // 向量是结构体,值类型,须要总体赋值 transform.position = new Vector3(3, 3, 3); Vector3 pos = transform.position; pos.x = 10; transform.position = pos; /* 静态方法 */ // Angle(a,b):返回两个向量的夹角 Vector2 a = new Vector2(2, 2); Vector2 b = new Vector2(3, 4); Debug.Log(Vector2.Angle(a, b)); // ClampMagnitude(a,length):限定长度,若是a>length,将向量a按比例缩小到长度为length Debug.Log(Vector2.ClampMagnitude(b, 2)); // Distance(a,b):返回两个向量(点)之间的距离 Debug.Log(Vector2.Distance(a, b)); // Lerp(a,b,x):在向量a,b之间取插值。最终值为(a.x + a.x * (b.x - a.x), a.y + a.y * (b.y - a.y)) Debug.Log(Vector2.Lerp(a, b, 0.5f)); Debug.Log(Vector2.LerpUnclamped(a, b, 0.5f)); // Max,Min:返回两向量最大最小 Debug.Log(Vector2.Max(a, b)); // + - * /:向量之间能够加减,不能乘除,能够乘除普通数字 Vector2 res = b - a;//1,2 print(res); print(res * 10); print(res / 5); print(a + b); print(a == b); } public Vector2 a = new Vector2(2, 2); public Vector2 target = new Vector2(10, 3); void Update() { // MoveTowards(a,b,speed):从a到b,速度为speed a = Vector2.MoveTowards(a, target, Time.deltaTime); } }
静态方法:
Range(a,b):生成>=a且<b的随机数 若a和b都为整数,则生成整数
InitState(seed):使用随机数种子初始化状态
Random.InitState((int)System.DateTime.Now.Ticks);
静态变量:
value:生成0到1之间的小数,包括0和1
state:获取当前状态(即随机数种子)
rotation:获取随机四元数
insideUnitCircle:在半径为1的圆内随机生成位置(2个点)
transition.position = Random.insideUnitCircle * 5; 在半径为5的圆内随机生成位置
insideUnitSphere:在半径为1的球内随机生成位置(3个点)
cube.position = Random.insideUnitSphere * 5;
using System.Collections; using System.Collections.Generic; using UnityEngine; public class API12Random : MonoBehaviour { void Start() { Random.InitState((int)System.DateTime.Now.Ticks); print(Random.Range(4, 10)); print(Random.Range(4, 5f)); } void Update() { if (Input.GetKeyDown(KeyCode.Space)) { print(Random.Range(4, 100)); print((int)System.DateTime.Now.Ticks); } //cube.position = Random.insideUnitCircle * 5; this.transform.position = Random.insideUnitSphere * 5; } }
一个物体的transform组件中,rotation是一个四元数
using System.Collections; using System.Collections.Generic; using UnityEngine; public class API13Quaternion : MonoBehaviour { void Start() { // rotation:四元数 // eulerAngles:欧拉角,rotation中的x,y,z //this.transform.rotation = new Vector3(10, 0, 0); 错误,左边是四元数,右边是欧拉角 this.transform.eulerAngles = new Vector3(10, 0, 0); print(this.transform.eulerAngles); print(this.transform.rotation); // Euler:将欧拉角转换为四元数 // eulerAngles:将四元数转换为欧拉角 this.transform.eulerAngles = new Vector3(45, 45, 45); this.transform.rotation = Quaternion.Euler(new Vector3(45, 45, 45)); print(this.transform.rotation.eulerAngles); } public Transform player; public Transform enemy; void Update() { // LookRotation:控制Z轴的朝向,通常处理某个物体望向某个物体 案例:主角望向敌人 // Lerp:插值,比Slerp快,但当角度太大的时候,没Slerp效果好 // Slerp:插值 案例:主角缓慢望向敌人 if (Input.GetKey(KeyCode.Space)) { Vector3 dir = enemy.position - player.position; dir.y = 0; Quaternion target = Quaternion.LookRotation(dir); player.rotation = Quaternion.Lerp(player.rotation, target, Time.deltaTime); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class API14RigidbodyPosition : MonoBehaviour { public Rigidbody playerRgd; public Transform enemy; public int force = 10; void Update() { // position:能够使用刚体的position来改变位置,忽然改变 playerRgd.position = playerRgd.transform.position + Vector3.forward * Time.deltaTime * 10; // MovePosition(Vector3 position):移动到目标位置,有插值的改变 playerRgd.MovePosition(playerRgd.transform.position + Vector3.forward * Time.deltaTime * 10); // rotation:能够使用刚体的rotation来控制旋转 // MoveRotation:旋转,有插值的改变 if (Input.GetKey(KeyCode.Space)) { Vector3 dir = enemy.position - playerRgd.position; dir.y = 0; Quaternion target = Quaternion.LookRotation(dir); playerRgd.MoveRotation(Quaternion.Lerp(playerRgd.rotation, target, Time.deltaTime)); } // AddForce:给物体添加一个力 playerRgd.AddForce(Vector3.forward * force); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class API15Camera : MonoBehaviour { private Camera mainCamera; void Start() { // 获取摄像机 //mainCamera= GameObject.Find("MainCamera").GetComponent<Camera>(); mainCamera = Camera.main; } void Update() { // ScreenPointToRay:把鼠标点转换为射线 Ray ray = mainCamera.ScreenPointToRay(Input.mousePosition); // 射线碰撞到的游戏物体 RaycastHit hit; bool isCollider = Physics.Raycast(ray, out hit); //射线检测 // 若是碰撞到物体,输出物体名字 if (isCollider) { Debug.Log(hit.collider); } Ray ray = mainCamera.ScreenPointToRay(new Vector3(200, 200, 0)); Debug.DrawRay(ray.origin, ray.direction * 10, Color.yellow); } }
Application Datapath:
using System.Collections; using System.Collections.Generic; using UnityEngine; public class API16Application_xxxPath : MonoBehaviour { void Start() { // 数据路径,工程路径 print(Application.dataPath); // 能够经过文件流读取的数据 // 注:单首创建StreamingAssets文件夹,在此文件夹中的数据打包的时候不会进行处理 print(Application.streamingAssetsPath); // 持久化数据 print(Application.persistentDataPath); // 临时缓冲数据 print(Application.temporaryCachePath); } }
Application 经常使用:
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class API17Application : MonoBehaviour { void Start() { print(Application.identifier);// 标识 print(Application.companyName);// 公司名 print(Application.productName);// 产品名字 print(Application.installerName);// 安装名 print(Application.installMode); print(Application.isEditor); print(Application.isFocused); print(Application.isMobilePlatform); print(Application.isPlaying); print(Application.isWebPlayer); print(Application.platform); print(Application.unityVersion); print(Application.version); print(Application.runInBackground); Application.Quit();// 退出应用 Application.OpenURL("www.sikiedu.com");// 打开一个网址 //Application.CaptureScreenshot("游戏截图"); // 弃用 UnityEngine.ScreenCapture.CaptureScreenshot("游戏截图");// 截图,参数是保存截图的名字 } void Update() { if (Input.GetKeyDown(KeyCode.Space)) { //UnityEditor.EditorApplication.isPlaying = false; SceneManager.LoadScene(1); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class API18SceneManager : MonoBehaviour { void Start() { // 当前加载的场景数量 print(SceneManager.sceneCount); // 在BuildSetting里的场景数量 print(SceneManager.sceneCountInBuildSettings); // 获得当前场景 经过name能够得到名字 print(SceneManager.GetActiveScene().name); // 根据index获取场景,注意index只能是已经加载场景的 print(SceneManager.GetSceneAt(0).name); SceneManager.activeSceneChanged += OnActiveSceneChanged; SceneManager.sceneLoaded += OnSceneLoaded; } // 场景改变事件(要卸载的场景,要加载的场景) void OnActiveSceneChanged(Scene a, Scene b) { print(a.name); print(b.name); } // 加载场景(加载的场景,加载的模式) void OnSceneLoaded(Scene a, LoadSceneMode mode) { print(a.name + "" + mode); } void Update() { if (Input.GetKeyDown(KeyCode.Space)) { // LoadScene:加载场景,能够经过名字或者序号加载 // LoadSceneAsync:异步加载,能够取得加载场景的进度 //SceneManager.LoadScene(1); //SceneManager.LoadScene("02 - MenuScene"); print(SceneManager.GetSceneByName("02 - MenuScene").buildIndex); SceneManager.LoadScene(1); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Player : MonoBehaviour { void Update () { // 建立一条射线:new Ray(起点,方向); Ray ray = new Ray(transform.position+transform.forward, transform.forward); // 检测碰撞:返回值表示是否碰撞到物体 Physics.Raycast(射线[, 距离]); //bool isCollider = Physics.Raycast(ray); //无限距离 //bool isCollider = Physics.Raycast(ray, 1); //检测1米距离 // 检测碰撞到哪一个物体: Physics.Raycast(射线, 碰撞信息); RaycastHit hit; //bool isCollider = Physics.Raycast(ray, out hit); // 碰撞检测时只检测某些层: Physics.Raycast(射线, 距离, 检测层); // Mathf.Infinity表示无限距 bool isCollider = Physics.Raycast(ray, Mathf.Infinity, LayerMask.GetMask("Enemy1", "Enemy2", "UI")); Debug.Log(isCollider); //Debug.Log(hit.collider); //Debug.Log(hit.point); //注:射线检测的重载方法有不少,不止以上几种 //注:若是是2D的射线检测,要使用Physics2D.Raycast(),使用时要保证物体添加了2D碰撞器 //注:上面的方法只会检测碰撞到的第一个物体,若是要检测碰撞到的全部物体,使用RaycastAll(),返回RaycastHit数组 } }
1 拖拽:
2 代码添加:
using System.Collections; using System.Collections.Generic; using System; using UnityEngine; using UnityEngine.UI; public class UIEventManager : MonoBehaviour { public GameObject btnGameObject; public GameObject sliderGameObject; public GameObject dropDownGameObject; public GameObject toggleGameObject; // Use this for initialization void Start () { btnGameObject.GetComponent<Button>().onClick.AddListener(this.ButtonOnClick); sliderGameObject.GetComponent<Slider>().onValueChanged.AddListener(this.OnSliderChanged); dropDownGameObject.GetComponent<Dropdown>().onValueChanged.AddListener(this.OnDropDownChanged); toggleGameObject.GetComponent<Toggle>().onValueChanged.AddListener(this.OnToggleChanged); } void ButtonOnClick() { Debug.Log("ButtonOnClick"); } void OnSliderChanged(float value) { Debug.Log("SliderChanged:" + value); } void OnDropDownChanged(Int32 value) { Debug.Log("DropDownChanged:" + value); } void OnToggleChanged(bool value) { Debug.Log("ToggleChanged:" + value); } // Update is called once per frame void Update () { } }
3 经过实现接口:经过这种方式,只能监听当前UGUI组件
鼠标相关事件或拖拽相关事件的实现
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.EventSystems; using System; //interface public class UIEventManager2 : MonoBehaviour//, IPointerDownHandler,IPointerClickHandler,IPointerUpHandler,IPointerEnterHandler,IPointerExitHandler ,IBeginDragHandler,IDragHandler,IEndDragHandler,IDropHandler { public void OnBeginDrag(PointerEventData eventData) { Debug.Log("OnBeginDrag"); } public void OnDrag(PointerEventData eventData) { Debug.Log("OnDrag"); } public void OnDrop(PointerEventData eventData) { Debug.Log("OnDrop"); } public void OnEndDrag(PointerEventData eventData) { Debug.Log("OnEndDrag"); } public void OnPointerClick(PointerEventData eventData) { Debug.Log("OnPointerClick"); } public void OnPointerDown(PointerEventData eventData) { Debug.Log("OnPointerDown"); } public void OnPointerEnter(PointerEventData eventData) { Debug.Log("OnPointerEnter"); } public void OnPointerExit(PointerEventData eventData) { Debug.Log("OnPointerExit"); } public void OnPointerUp(PointerEventData eventData) { Debug.Log("OnPointerUp"); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class WWWTest : MonoBehaviour { public string url = "https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=2622066562,1466948874&fm=27&gp=0.jpg"; IEnumerator Start() { WWW www = new WWW(url); yield return www; Renderer renderer = GetComponent<Renderer>(); renderer.material.mainTexture = www.texture; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerCC : MonoBehaviour { public float speed = 3; private CharacterController cc; // Use this for initialization void Start () { cc = GetComponent<CharacterController>(); } void Update () { float h = Input.GetAxis("Horizontal"); float v = Input.GetAxis("Vertical"); cc.SimpleMove(new Vector3(h, 0, v) * speed);//有重力效果 //cc.Move(new Vector3(h, 0, v) * speed * Time.deltaTime);//无重力效果 Debug.Log(cc.isGrounded);//是否在地面 } private void OnControllerColliderHit(ControllerColliderHit hit)//自带的检测碰撞事件 { Debug.Log(hit.collider); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class MeshAndMat : MonoBehaviour { public Mesh mesh; private Material mat; void Start () { //GetComponent<MeshFilter>().sharedMesh = mesh;//改变网格,样子跟着变 //Debug.Log(GetComponent<MeshFilter>().mesh == mesh);//改变网格,样子不变 mat = GetComponent<MeshRenderer>().material; } void Update () { mat.color = Color.Lerp(mat.color, Color.red, Time.deltaTime);//改变材质颜色 } }
GetComponent<Rigidbody2D>() 代替 rigidbody2D
GetComponent<Rigidbody>() 代替 rigidbody
GetComponent<AudioSource>() 代替 audio
Unity 5.3:
ParticleSystem main = smokePuff.GetComponent<ParticleSystem>();
main.startColor
Unity 5.5+:
ParticleSystem.MainModule main = smokePuff.GetComponent<ParticleSystem>().main;
main.startColor
SceneManagement 代替 Application
OnLevelWasLoaded() 在 Unity 5中被弃用了,使用OnSceneLoaded代替
public class UnityAPIChange : MonoBehaviour { private Rigidbody rgd; void Start () { rgd = GetComponent<Rigidbody>(); SceneManager.sceneLoaded += this.OnSceneLoaded; } void OnSceneLoaded(Scene scene, LoadSceneMode mode) { } void Update () { //rigidbody.AddForce(Vector3.one); //rgd.AddForce(Vector3.one); //audio.Play();//弃用的 //GetComponent<AudioSource>().Play(); //GetComponent<Rigidbody2D>(); //GetComponent<MeshRenderer>(); //Application.LoadLevel("Level2"); SceneManager.LoadScene("Scene2"); Scene scene = SceneManager.GetActiveScene(); SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex); } private void OnLevelWasLoaded(int level) 弃用 { } }