unity common API (a)

unity common API (a)

Personal bad English, so do the Chinese API is part of the code and explain 2018.1 are derived from this document: description link

Video link: Click on the link

unity comes with some functions

  1. Awake: Always and this function is called after the instantiation of the preform before any Start functions. (If the game objects during startup is inactive, it will be activated after the call Awake.)

  2. Start: not very urgent initialization, general Start on the inside to do. Call just before the Update function is called the first time

  3. Reset: When calling Reset for the first time can be attached to objects in the script and use Reset attribute initialization script command

  4. Update: called once per frame Update. This is the main function is used to update the frame.

  5. FixedUpdate: call at the same time interval, with the mechanics updated effects. Executed before Update.

  6. LateUpdate: Update and FixedUpdate call after call. Update on the movement of ordinary people, rather follow changes in the camera into FixedUpdate. Make sure that both independent.

  7. OnDestory: Called when an object is deleted.

  8. OnEnable :( invoked only when the object is active) This function is called immediately after the object is enabled. When creating MonoBehaviour instances (such as when loading a game level or instantiate an object with scripting components) will execute this call.

  9. OnDisable: Called when an object is disabled.

    Call to order:

    8y9KpR.png

Time class

  1. deltaTime: a completion time used (in seconds) (read only).

  2. fixedDeltaTime: performing a physical update and other fixed frame rate (e.g., the FixedUpdate MonoBehaviour) the time interval (in seconds).

  3. fixedTime: FixedUpdate started last time (read-only). This is the time since the start of the game (in seconds).

  4. frameCount: total number of frames has elapsed (read-only).

  5. The actual time (read-only) since the start of the game: realtimeSinceStartup.

  6. smoothDeltaTime: Time.deltaTime after smoothing processing (read-only).

  7. time: In the beginning of the frame (read-only). This is the time since the start of the game (in seconds).

  8. timeScale: the passage of time scaling. It can be used for slow motion.

  9. timeSinceLevelLoad: the time since the start of frame (read-only). This is a self-loading time (in seconds) since the last checkpoint.

Performance Testing

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

Make objects move forward

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

GameObject class

  1. Creating an object in three ways

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

    // 添加刚体
    go.AddComponent<Rigidbody>();
    // 添加 脚本
    go.AddComponent<API01Event>();  // API01Event 是脚本
  3. activeInHierarchy: GameObject defined in the Scene is active.

    Debug.Log(go.activeInHierarchy); // True
    go.SetActive(false);
    Debug.Log(go.activeInHierarchy); // False
  4. Tag: label this game objects.

  5. name: name of the object.

    Debug.Log(go.name);
    Debug.Log(go.GetComponent<Transform>().name)//获取组件的名字其实获取的是物体的名字
  6. layer: layer of the game object is located.

  7. scene: The scene GameObject belongs.

Public Functions

  1. AddComponent: Add the component class name is className to the game object.

    go.AddComponent<Rigidbody>();
  2. ComPareTag: If the game object type for the type of attached components, it is returned, otherwise null.

  3. SetActive: activate / deactivate this GameObject.

  4. SendMessage: Invokes the method named methodName on this game object each MonoBehaviour.

  5. BroadcastMessage: Invokes the method named methodName on this game objects or any of its entries each MonoBehaviour.

    target.BroadcastMessage("Attack",null,SendMessageOptions.DontRequireReceiver);//如果有接受者则发送,如果没有不报错
    void Attack() //当一个物体的脚本里拥有此方法则会被调用(子类也会调用)
    {
     Debug.Log(this.gameObject + "正在攻击");
    }
  6. SendMessageUpwards: Invokes the method named methodName on this target in each game or each parent MonoBehaviour this behavior.

  7. GetCompont: If the game object type for the type of attached components, it is returned, otherwise null.

    Cube cube = target.GetComponent<Cube>(); //类
    Transform t = target.GetComponent<Transform>();
  8. GetComponts: Returns type GameObject for all type of components.

    Cube[] cubes = target.GetComponents<Cube>();
    cubes = target.GetComponentsInChildren<Cube>();
    foreach(Cube c in cubes)
    {
          Debug.Log(c);
    }
  9. GetComponentsInChildren: using depth first search returns GameObject or any of its key components of type type.

  10. GetComponentsInParant: Returns the parent GameObject, or any type of type of components.

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: create a game object from the original mesh renderer and the corresponding collision body has.

  2. Find: Find GameObject by name, and then return it.

    GameObject go = GameObject.Find("Main Camera");
  3. FindGameObjectWithTag: a list of activities to mark the return of GameObject tag. If GameObject not found, an empty array is returned.

    GameObject[] gos= GameObject.FindGameObjectsWithTag("MainCamera");
  4. Destroy: Delete GameObject, components or resources. It will not be recovered immediately

    Destroy(this);(一般是脚本)(可以销毁物体也可以销毁组件)
    Destroy(gameObject,5); //(5秒后销毁)
  5. DontDestroyOnLoad: When loading a new scene, does not automatically destroy the object / target /.

  6. FindObjectOfType: Returns the first activation object type for the type of loaded.

  7. FindObjectsOfType: type returns a list of all types of activated objects are loaded.

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

MonoBehaviour

  1. Invoke: invoke method methodName after time seconds.

    Invoke("Attack", 3);
    void Update () {
        bool res = IsInvoking("Attack");
        print(res);
    }
    void Attack()
    {
         Debug.Log("正在攻击目标");
    }
  2. InvokeRepeating: methodName method call after the second time, and then call every repeatRate seconds.

    InvokeRepeating("Attack", 4, 2);//第四秒开始调用第一次,之后每2秒调用一次
  3. CancleInvoke: cancel all call Invoke on the MonoBehaviour.

    CancelInvoke("Attack");

    Coroutine

  4. When using coroutines requires the following keywords:

    1. Function return value is IEnmerator
    2. To use the function return yield return xxx
    3. When calling coroutine method we want to use 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); // 暂停
         }
     }

    Press the spacebar following effects when executed unity:
    86k724.gif

  5. StopCoroutine: Stop collaborative program first collaborative program or store named methodName running on the behavior of the routine

      // 第一种停止方式
      Coroutine A = StartCoroutine(coroutineA());
      StopCoroutine(A);
      // 第二种停止方式
      IEnumerator DemoFuntion(){
           ...
      }
      IEnumerator coroutine = DemoFuntion();
      StartCoroutine(coroutine);
      StopCoroutine(coroutine);
  6. ** StopAllCoroutines: Stop all coroutines running on the act.

Guess you like

Origin www.cnblogs.com/Dvelpro/p/12528864.html