Mathf中的常用方法
ClosePowerOfTwo():取得离2的次方最近的数
Ceil:取大的数,向上取整
Floor:取小的数,向下取整
Lerp:
LerpAngle:
Pow(f,p):取得f的p次方
Sqrt:取得参数的平方根
Mathf中的常用方法
ClosePowerOfTwo():取得离2的次方最近的数
Ceil:取大的数,向上取整
Floor:取小的数,向下取整
Lerp:
LerpAngle:
Pow(f,p):取得f的p次方
Sqrt:取得参数的平方根
Mathf中的Clamp限定方法
Abs:取绝对值
Ceil:向上取整,返回Float类型的整数
CeilInt:向上取整,返回Int类型的整数
Clamp:夹紧,如果value值小于min则返回min值,如果value值大于max值,则返回max值,如果在min和value之间则返回value本身值,用于判断某个值在哪个范围之内(生命系统用)
public class MathfCS : MonoBehaviour {
public Transform cube;
void Update()
{
cube.position = new Vector3(Mathf.Clamp(Time.time, 1.0f, 3.0f), 0, 0);//限定他的运动在1到3之间
}
}
Clamp01:把Clamp的值限定在0-1之间
Mathf里面的静态常量
public class MathfCS : MonoBehaviour {
// Use this for initialization
void Start () {
print(Mathf.Deg2Rad);//度数转弧度
print(Mathf.Rad2Deg);//弧度转度数
print(Mathf.Infinity);//表示无限大的数
print(Mathf.NegativeInfinity); //表示负的无限大的数
print(Mathf.PI);
print(Mathf.Epsilon);//非常非常小的数,但不是负数
}
// Update is called once per frame
}
跟鼠标相关事件函数OnMouseXXX讲解
鼠标的基本操作函数:
public class MouseCS : MonoBehaviour {
void OnMouseDown()//鼠标按下执行一次
{
print("Down");
}
void OnMouseUp()//鼠标抬起执行一次
{
print("Up");
}
void OnMouseDrag()//鼠标在物体上按住拖动一直执行
{
print("Drag");
}
void OnMouseEnter()//鼠标移到物体上执行一次
{
print("Enter");
}
void OnMouseExit()//鼠标移除物体执行一次
{
print("Exit");
}
void OnMouseOver()//鼠标在物体上一直执行
{
print("Over");
}
void OnMouseUpAsButton()//在同一物体,按下并抬起鼠标,会触发一次,在不同物体间进行一次按下抬起动作不会触发
{
print("Button"+gameObject);
}
}
Coroutine协程的开启和关闭
法一:
private IEnumerator ie;
void Update () {
if (Input.GetKeyDown(KeyCode.Space))
{
ie = Fade();
StartCoroutine(ie);//实现白到红的渐变
}
if (Input.GetKeyDown(KeyCode.S))
{
StopCoroutine(ie);//跟上面的调用方式一致,才能关闭(这里都用ie来开启和关闭)
}
}
//下面是Fade()的代码,未写
法二:
void Update () {
if (Input.GetKeyDown(KeyCode.Space))
{
StartCoroutine("Fade");
}
if (Input.GetKeyDown(KeyCode.S))
{
StopCoroutine("Fade");
}
}
使用Coroutine实现颜色动画渐变
实现黑白渐变动画
public class CoroutineCS : MonoBehaviour {
public GameObject cube;
void Update () {
if (Input.GetKeyDown(KeyCode.Space))
{
StartCoroutine(Fade());//实现黑到白的渐变
}
}
IEnumerator Fade()
{
for (float i = 0; i <= 1; i += 0.1f)//i代表颜色
{
cube.GetComponent<MeshRenderer>().material.color = new Color(i, i, i, i);//四个i分别代表R,G,B和透明度
yield return new WaitForSeconds(0.1f);//暂停0.1秒
}
}
}
void Update () {
if (Input.GetKeyDown(KeyCode.Space))
{
StartCoroutine(Fade());//实现白到红的渐变
}
}
IEnumerator Fade()
{
for (; ; )//死循环
{
Color color = cube.GetComponent<MeshRenderer>().material.color;//获取cube的color属性
Color newcolor = Color.Lerp(color, Color.red, 0.02f);//设置一个新颜色:红色,并设置0.02秒变换一次
cube.GetComponent<MeshRenderer>().material.color = newcolor;//把新颜色付给他
yield return new WaitForSeconds(0.02f);//暂停0.02秒
if (Mathf.Abs(Color.red.g - newcolor.g) <= 0.01f)//当新颜色的g与标准红色相差小于0.01,结束循环
{
break;
}
}
}
什么是协程、它是如何执行的
协程(Coroutine):
public class CoroutineCS : MonoBehaviour {
public GameObject cube;
// Use this for initialization
void Start () {
print("hahahahah");
StartCoroutine(ChangeColor());//通过协程,调用ChangeColor方法,调用之后,start和ChangeColor同步进行
print("dcdd");
}
// Update is called once per frame
void Update () {
}
/// <summary>
/// 不会阻塞当前方法的运行
/// 自身可以暂停运行
/// 返回值为IEnumerator
/// 返回参数的时候使用yield return null/0
/// 协程方法的调用:StartCoroutine(method())
/// </summary>
/// <returns></returns>
IEnumerator ChangeColor()
{
print("color");
cube.GetComponent<MeshRenderer>().material.color = Color.blue;
print("aaaaacolor");
yield return null;
}
}
MonoBehaviour中Invoke的使用
Invoke:调用时Invoke中的方法不会立即被调用,会添加到队列里面等待
IsInvoking:判断某个方法是否正在被调用,在队列中存在显示True
InvokeRepeating:每间隔几秒调用一次,里面的方法会一直在队列中
public class InvokeCS : MonoBehaviour {
// Use this for initialization
void Start () {
//Invoke("Attack", 3);//等待3秒调用Attack方法,不调用前在队列中等待
InvokeRepeating("Attack", 4, 2);//等待4秒开始调用,然后每隔2秒调用一次,Attack一直在队列中
}
// Update is called once per frame
void Update () {
bool rs =IsInvoking("Attack");//判断这个方法是否正在被调用,未调用显示True
print(rs);
}
void Attack()
{
print("正在攻击");
}
}
MonoBehaviour里面的常用变量
isActiveAndEnabled:判断组件是否被激活
EnAble:设置是否激活(值为True或False)
tag:获取组件所在的游戏物体的标签
gameObject:获取组件所在的游戏物体
name:获取游戏物体的名字
print:输出游戏日志,必须在MonoBehaviour里面调用
public class MonoBehaviourCS : MonoBehaviour {
public Cube cube;
// Use this for initialization
void Start () {
Debug.Log(this.isActiveAndEnabled);//判断组件是否被激活
Debug.Log(this.enabled);//设置是否激活(值为True或False)
enabled = false;
Debug.Log(name);
Debug.Log(tag);//获取组件所在的游戏物体的标签
Debug.Log(gameObject);//获取组件所在的游戏物体
Debug.Log(transform);
print("aaaa");
Debug.Log(cube.isActiveAndEnabled);
Debug.Log(cube.enabled);
cube.enabled = false;
Debug.Log(cube.name);
Debug.Log(cube.tag);
Debug.Log(cube.gameObject);
Debug.Log(cube.transform);
}

MonoBehaviour总览
这节没什么想记的
得到组件的各种方法函数
public class GetComponentCS : MonoBehaviour {
public GameObject target;
// Use this for initialization
void Start () {
Cube cube = target.GetComponent<Cube>();//得到Cube组件
Transform t = target.GetComponent<Transform>();//得到Transform组件
Debug.Log(cube);//输出
Debug.Log(t);
Debug.Log("--------------------------");
Cube[] cubes = target.GetComponents<Cube>();//得到target上所有的Cube组件
Debug.Log(cubes.Length);//输出长度
Debug.Log("--------------------------");
cubes = target.GetComponentsInChildren<Cube>();//得到target的所有的孩子以及其自身上的Cube组件
foreach (Cube c in cubes)
{
Debug.Log(c);
}
Debug.Log("--------------------------");
cubes = target.GetComponentsInParent<Cube>();//得到target的所有的孩子以及其自身上的Cube组件
foreach (Cube c in cubes)
{
Debug.Log(c);
}
Debug.Log("--------------------------");
}
// Update is called once per frame
}

游戏物体间消息的发送和接收
通过对象来调用的方法 (public Functions)
BroadcastMessage:广播一个消息,调用方法
自身和其子方法都会调用
public class MessageCeS : MonoBehaviour {
public GameObject target;
// Use this for initialization
void Start () {
//括号中写具体的方法名,首字母要带大写,BroadcastMessage调用带有Attack方法的物体与其子物体
target.BroadcastMessage("Attack", null, SendMessageOptions.DontRequireReceiver);
}
// Update is called once per frame
}
public class Cube : MonoBehaviour {
// Use this for initialization
void Attack()
{
Debug.Log(this.gameObject+"正在攻击");
}
}

SendMessage:针对某个目标直接发送消息
不会影响其子物体
target.SendMessage("Attack", null, SendMessageOptions.DontRequireReceiver);

SendMessageUpwards:向上发送,调用当前物体与其父级(他的父级,他父级的父级.....)
target.SendMessageUpwards("Attack", null, SendMessageOptions.DontRequireReceiver);
GameObject独有的静态方法
静态方法都是首字母大写的
Find():根据名字查找,遍历场景中的所有游戏物体,用的少
FindGameObjectWithTag():通过标签来查找相同标签游戏物体
FindGameObjectsWithTag():通过标签来查找所有相同标签游戏物体
//Find
GameObject go = GameObject.Find("Main Camera");
go.SetActive(false);//验证上一步是否运行
//FindGameObjectsWithTag
GameObject[] gos = GameObject.FindGameObjectsWithTag("MainCamera");
gos[0].SetActive(false);

UnityEngine下Object用有的静态方法
静态方法要用类名来调用,不能通过对象调用
Destroy:可以销毁游戏物体,也可以销毁组件
DonDestroyOnLoad:
在A场景跳转B场景时,A中所有游戏物体都会销毁。
调用这个方法的游戏物体可以不销毁,既场景切换时,这个游戏物体始终存在
FindObjectOfType:根据组件类型查找组件,find从全局搜索,如果有多个,只找到第一个返回一个
FindObjectsOfType:找到场景中所有的组件,并返回一个数组(既是静态方法,又是成员方法)
Light light = FindObjectOfType<Light>();
light.enabled = false;//没有灯光了
Transform[] ts = FindObjectsOfType<Transform>();//不查找未激活的物体
foreach (var item in ts)
{
Debug.Log(item);
}

GameObject、Component和Object的千丝万缕的关系


GameObject go = GameObject.CreatePrimitive(PrimitiveType.Sphere);
Debug.Log(go.name);
Debug.Log(go.GetComponent<Transform>().name);//两者输出的名字一样,都是Sphere
如何禁用和启用一个游戏物体
transform:游戏中的任何物体都要有transform组件,是用来定位的,每个游戏物体有且仅有一个,不能被移除
tag:通过tag来区分场景中的游戏物体
activeInHieaarchy:判断游戏物体是否处于激活状态
activeSelf:看物体的active属性是否被禁用,如果他的父物体被禁用,他本身的active还是True
GameObject go = GameObject.CreatePrimitive(PrimitiveType.Sphere);//创建物体
Debug.Log(go.activeInHierarchy);//True
go.SetActive(false);
Debug.Log(go.activeInHierarchy);//False
Debug.Log(go.tag);//未设置标签输出Untagged
如何给游戏物体通过代码添加组件(通过代码添加)
关键字为:AddComponent
用法:实例名.AddComponent<组件名>;
GameObject go = GameObject.CreatePrimitive(PrimitiveType.Sphere);
go.AddComponent<Rigidbody>();//可以为组件
go.AddComponent<TimeCeShi>();//可以为自定义的脚本
创建游戏物体的三种方法Gameobject
1.new GameObject
2.GameObject.Instantiate
3.GameObject.CreatePrimitive
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AAGameObjectCeShi : MonoBehaviour {
public GameObject prefab;
// Use this for initialization
void Start () {
//第一种创建方法:new一个GameObject
GameObject go = new GameObject("Cube");
//第二种创建方法:instantiate实例化一个prefab(预制体)
GameObject.Instantiate(prefab);
//第三种创建方法:CreatePrimitive
GameObject.CreatePrimitive(PrimitiveType.Plane);
}
// Update is called once per frame
}
TimedeltaTime和realTimeSinceStartup的使用
Time.daltaTime:用来做物体的运动,动画相关的东西
用Time.daltaTime时,物体的运动,不会随帧数的改变而改变
Time.timeScale
Time.realTimeSinceStartup:用来测试性能