unity常用API(一)

个人英语不好,所以看的是2018.1 的中文API 部分代码和解释都来源于此文档:原文链接

视频链接:点击链接

[TOC]

unity自带的一些函数

  1. Awake:始终在任何 Start 函数之前并在实例化预制件之后调用此函数。(如果游戏对象在启动期间处于非活动状态,则在激活之后才会调用 Awake。)

  2. Start:不是很紧急的初始化,一般放在Start里面来做。仅在Update函数第一次被调用前调用

  3. Reset:调用 Reset 可以在脚本首次附加到对象时以及使用 Reset 命令时初始化脚本的属性

  4. Update:每帧调用一次 Update。这是用于帧更新的主要函数。

  5. FixedUpdate:以相同时间间隔调用,用在力学更新效果中。执行在Update之前。

  6. LateUpdate:在Update和FixedUpdate调用之后调用。一般人物的移动放在Update中,而摄像机的跟进变化放到FixedUpdate中。确保两个独立。

  7. OnDestory:物体被删除时调用。

  8. OnEnable:(仅在对象处于激活状态时调用)在启用对象后立即调用此函数。在创建 MonoBehaviour 实例时(例如加载关卡或实例化具有脚本组件的游戏对象时)会执行此调用。

  9. OnDisable:物体被禁用时调用。

    调用顺序:

    8y9KpR.png

Time类

  1. deltaTime: 完成上一帧所用的时间(以秒为单位)(只读)。

  2. fixedDeltaTime:执行物理和其他固定帧率更新(如 MonoBehaviour 的 FixedUpdate)的时间间隔(以秒为单位)。

  3. fixedTime:最近一次 FixedUpdate 已启动的时间(只读)。此为自游戏启动以来的时间(以秒为单位)。

  4. frameCount:已经过的总帧数(只读)。

  5. realtimeS***artup:游戏开始以来的实际时间(只读)。

  6. smoothDeltaTime:经过平滑处理的 Time.deltaTime(只读)。

  7. time:该帧开始的时间(只读)。此为自游戏启动以来的时间(以秒为单位)。

  8. timeScale:时间流逝的缩放。可用于慢动作效果。

  9. timeSinceLevelLoad:该帧开始以来的时间(只读)。此为自加载上一个关卡以来的时间(以秒为单位)。

    测试性能

    float timeStart = Time.realtimeS***artup;
    for (int i = 0; i < 10000; i++)
    {
         Method();
    }
    float timeEnd = Time.realtimeS***artup;
    Debug.Log(timeEnd-timeStart);
    

    使物体向前移动

    cube.transform.Translate(Vector3.forward * Time.deltaTime);

GameObject 类

  1. 创建物体的三种方式

    // 第一种
    GameObject go= new GameObject("cube");
    // 克隆一个已有的
    GameObject.Instantiate(prefab);
    // 创建基本的物体
    GameObject go =GameObject.CreatePrimitive(PrimitiveType.Cube);
  2. 添加组件

    // 添加刚体
    go.AddComponent<Rigidbody>();
    // 添加 脚本
    go.AddComponent<API01Event>();  // API01Event 是脚本
  3. activeInHierarchy:定义 GameObject 在 Scene 中是否处于活动状态。

    Debug.Log(go.activeInHierarchy); // True
    go.SetActive(false);
    Debug.Log(go.activeInHierarchy); // False
  4. Tag:此游戏对象的标签。

  5. name:对象的名称。

    Debug.Log(go.name);
    Debug.Log(go.GetComponent<Transform>().name)//获取组件的名字其实获取的是物体的名字
  6. layer: 该游戏对象所在的层。

  7. scene:该 GameObject 所属的场景。

Public Functions

  1. AddComponent : 将名为 className 的组件类添加到该游戏对象。

    go.AddComponent<Rigidbody>();
  2. ComPareTag : 如果游戏对象附加了类型为 type 的组件,则将其返回,否则返回 null。

  3. SetActive : 激活/停用此 GameObject。

  4. SendMessage : 调用此游戏对象中的每个 MonoBehaviour 上名为 methodName 的方法。

  5. BroadcastMessage : 调用此游戏对象或其任何子项中的每个 MonoBehaviour 上名为 methodName 的方法。

    target.BroadcastMessage("Attack",null,SendMessageOptions.DontRequireReceiver);//如果有接受者则发送,如果没有不报错
    void Attack() //当一个物体的脚本里拥有此方法则会被调用(子类也会调用)
    {
        Debug.Log(this.gameObject + "正在攻击");
    }
  1. SendMessageUpwards : 调用此游戏对象中的每个 MonoBehaviour 上或此行为的每个父级上名为 methodName 的方法。

  2. GetCompont:如果游戏对象附加了类型为 type 的组件,则将其返回,否则返回 null。

    Cube cube = target.GetComponent<Cube>(); //类
    Transform t = target.GetComponent<Transform>();
  3. GetComponts: 返回 GameObject 中类型为 type 的所有组件。

    Cube[] cubes = target.GetComponents<Cube>();
    cubes = target.GetComponentsInChildren<Cube>();
    foreach(Cube c in cubes)
    {
          Debug.Log(c);
    }
  4. GetComponentsInChildren: 使用深度首次搜索返回 GameObject 或其任何子项中类型为 type 的组件。

  5. GetComponentsInParant: 返回 GameObject 或其任何父项中类型为 type 的组件。

    Cube cube = target.GetComponent<Cube>();    // 获取单个
    Transform t = target.GetComponent<Transform>();
    Debug.Log(cube);
    Debug.Log(t);
    Debug.Log("---------------------------------");
    
    Cube[] cubes = target.GetComponents<Cube>();    // 获取多个
    Debug.Log(cubes.Length);
    Debug.Log("---------------------------------");
    
    cubes = target.GetComponentsInChildren<Cube>();    // 自己以及子类
    foreach (Cube c in cubes)
    {
       Debug.Log(c);
    }
    Debug.Log("---------------------------------");
    cubes = target.GetComponentsInParent<Cube>();
    foreach (Cube c in cubes)
    {
      Debug.Log(c);
    }

Static Functions

  1. CreatePrimitive : 创建一个具有原始网格渲染器和相应碰撞体的游戏对象.

  2. Find : 按 name 查找 GameObject,然后返回它。

    GameObject go = GameObject.Find("Main Camera");
  3. FindGameObjectWithTag : 返回标记为 tag 的活动 GameObject 的列表。如果未找到 GameObject,则返回空数组。

    GameObject[] gos= GameObject.FindGameObjectsWithTag("MainCamera");
  4. Destroy : 删除 GameObject、组件或资源。 不会被立即回收

    Destroy(this);(一般是脚本)(可以销毁物体也可以销毁组件)
    Destroy(gameObject,5); //(5秒后销毁)
  5. DontDestroyOnLoad:加载新场景时,不自动销毁对象 /target/。

  6. FindObjectOfType:返回第一个类型为 type 的已加载的激活对象。

  7. FindObjectsOfType:返回所有类型为 type 的已加载的激活对象的列表。

    Light light =FindObjectOfType<Light>(); //获取所有的灯
    light.enabled = false;

MonoBehaviour

  1. Invoke : 在 time 秒后调用 methodName 方法。

    Invoke("Attack", 3);
    void Update () {
        bool res = IsInvoking("Attack");
        print(res);
    }
    void Attack()
    {
         Debug.Log("正在攻击目标");
    }
  2. InvokeRepeating : 在 time 秒后调用 methodName 方法,然后每 repeatRate 秒调用一次。

    InvokeRepeating("Attack", 4, 2);//第四秒开始调用第一次,之后每2秒调用一次
  3. CancleInvoke : 取消该 MonoBehaviour 上的所有 Invoke 调用。

    CancelInvoke("Attack");

    协程

  4. 在使用协程的时候需要有以下几个关键词:

    1. 函数返回值是IEnmerator

    2. 函数返回时要使用 yield return xxx

    3. 调用协程方法时 我们要使用StartCoroutine(xxx())

      public GameObject cube;
      private void Update()
      {
          if (Input.GetKeyDown(KeyCode.Space))
          {
              StartCoroutine(Fade());
          }
      }
      
      IEnumerator Fade()
      {
          for (float i = 0; i <= 1; i += 0.1f)
          {    
              // 第一种方式
             //cube.GetComponent<MeshRenderer>().material.color = new Color(i,i,i,i);
              // 第二种方式
             Color color = cube.GetComponent<MeshRenderer>().material.color;
             Color newColor = Color.Lerp(color, Color.black,0.1f); // 向黑色逐渐靠近
             cube.GetComponent<MeshRenderer>().material.color = newColor;
             yield return new WaitForSeconds(0.1f); // 暂停
          }
      }

      unity执行时按下空格键 效果如下:
      86k724.gif

  5. StopCoroutine : 停止在该行为上运行的第一个名为 methodName 的协同程序或存储在 routine 中的协同程序

      // 第一种停止方式
      Coroutine A = StartCoroutine(coroutineA());
      StopCoroutine(A);
      // 第二种停止方式
      IEnumerator DemoFuntion(){
           ...
      }
      IEnumerator coroutine = DemoFuntion();
      StartCoroutine(coroutine);
      StopCoroutine(coroutine);
  6. StopAllCoroutines : 停止在该行为上运行的所有协程。