Unity中Start、Uptade、Awake和method的区别及调用顺序

1.在同一个脚本中,Start在Update之前执行;Start只执行一次,Update每帧都执行;一般将初始化的代码放在Start中,将随时间改变的代码放在Update(例如,移动要有时间,一般放在Update中)。这里每帧不和每秒对应,每帧对应的时间是不定的,每帧对应的时间为将Update执行完所需时间(一般可这样看,严格意义上不是这样)。

测试:

using UnityEngine;
using UnityEngine.UI;

public class Test : MonoBehaviour
{

    private int[] A=new int[10000];
    // Start is called before the first frame update
    void Start()
    {
        Debug.Log("执行Start");
    }

    // Update is called once per frame
    void Update()
    {
        for (int i = 0; i < 10000; i++)
        {
            int x = Random.Range(1, 10000);
            A[i] = x;
        }
        bubblesort1(A);
        Debug.Log("执行Update");

    }

    public void bubblesort1( int[] A)//用冒泡排序延时
    {       
        int n = A.Length;
        for (int i = 0; i < A.Length - 1; i++)
        {
            for (int j = 0; j < A.Length - 1; j++)
            {
                if (A[j] > A[j + 1])
                {
                    int temp = A[j];
                    A[j] = A[j + 1];
                    A[j + 1] = temp;
                }
            }
        }
    }
}

输出:

2.场景中有多个脚本时,会先执行完所有脚本的Start,然后在执行完所有脚本的Update;所有脚本的Start按照什么顺序来执行是不确定的,所以需要自己设计顺序。

3.当游戏在运行时需要加上一个新的脚本时,由于正在执行游戏中某个脚本的Update,如果用AddComponent给某GameObject添加新的脚本(原来游戏中没有出现)想直接调用该脚本中的方法,或者实例化出了某GameObject来获取其上挂在的某脚本直接调用该脚本中的方法时,如果方法内涉及初始化的数据,那么会报错。因为此时在执行Update,直到所有Update执行完后,才会在下一帧中执行新添加的脚本中的Start方法。

测试:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Test2 : MonoBehaviour
{
    private int x;
    // Start is called before the first frame update
    void Start()
    {
        x = 4;
        Debug.Log(x);
    }

    // Update is called once per frame
    void Update()
    {
        
    }

    public void Method()
    {
        Debug.Log(x);
    }
}
using UnityEngine;


public class Test : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        Debug.Log("Start");
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            transform.gameObject.AddComponent<Test2>().Method();
        }       
    }
}

输出:

4.Awake先于所有的Start执行,同Start一样只执行一次。在运行时实例化了一个预设体或者添加了一个脚本,Awake仍会执行,但Start不一定执行。如果实例化的物体本身是inactive的,那么Awake不会执行。

5.脚本的状态为enable时,Start才执行。

6.OnEable会紧随着Awake执行,他们两个会成对出现。

【未完待续。。。】

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值