多个协程的调用顺序,以及Update和Start的关系

经过测试,根据测试结果记录一下我的一些认识。如果有错误希望大家为我指出。

对Start的理解。

我认为Start只是一个普通函数,我理解为第一次Update时,在Update的最前面被调用一次。大概是这样:

    int index = 0;
    void Update()
    {
        if (index == 0)
        {
            Start();
        }
        index++;
        //然后是Update的代码
    }

之所以这样认为是,在Start里开启一个协程,那么在第一个Update里不会处理这个协程。而在Awake或者OnEnable里开启一个协程,那么这个协程这会被第一个Update处理。所以我认为按照上边的方式理解更说的过去。

关于Update和协程的调用顺序。

Unity在每刷新一帧时,先执行Update的代码,然后再执行协程yield return之后的代码。

多个协程的执行顺序

如果已经开启了若干协程,现在通过StartCoroutine开启一个协程A,那么在这次Update和之后的Update中,协程A在所有协程中被第一个处理。越是后来开启的协程,越被提前处理。

普通函数和Update函数的执行顺序

在GameObject B 加载一个GameObject A

using UnityEngine;
using System.Collections;

public class B : MonoBehaviour {
    public GameObject A;

    void Start () {
        GameObject A2 = Instantiate(Resources.Load("A")) as GameObject;
        A2.GetComponent().Function();
    }
}

using UnityEngine;
using System.Collections;
public class A : MonoBehaviour
{
    void Awake()
    {
        Debug.Log("Awake");
    }

    void Start()
    {
        Debug.Log("Start");
    }

    public void Function()
    {
        Debug.Log("Function");
    }

    void Update()
    {
        Debug.Log("Update");
    }
}

那么log的顺序是:Awake ,Function ,Start ,Update ,所以普通函数在Awake之后和Start之前执行。

你可能感兴趣的:(Unity3D,Unity-函数)