设置unity脚本的执行顺序

有时候,设置脚本的执行顺序还是很有必要的。我曾经遇到过这样的情况,中午去吃饭的时候程序还跑的好好的,到下午回来的时候却出现空对象异常的情况,后来我找到了错误,原来是代码的执行顺序的问题。

 

好了,废话不说了,看步骤吧!

步骤:

1 在unity场景中建立3个空的游戏物体,名称分别为:Script1,Script2,Script3

2 建立三个脚本,脚本名称为Script1.cs,Script2.cs,Script3.cs,对应编辑脚本如下:

 

Script1.cs

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

public class Script1 : MonoBehaviour {

	
	void Start () {
        Debug.Log("Script1执行!");
	}
	
	
	void Update () {
		
	}
}

Script2.cs

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

public class Script2 : MonoBehaviour {


	void Start () {
        Debug.Log("Script2执行!");
	}
	
	
	void Update () {
		
	}
}

 

Script3.cs

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

public class Script3 : MonoBehaviour {

	
	void Start () {
        Debug.Log("Script3执行!");
	}
	
	
	void Update () {
		
	}
}

3  分别为空游戏物体Script1,Script2,Script3对应添加脚本Script1.cs,Script2.cs,Script3.cs,注意,这时我添加脚本的顺序是,先为Script2添加脚本Script2.cs,再为Script1添加脚本Script1.cs,最后为Script3添加脚本Script3.cs

最后打印输出的结果如下图:

设置unity脚本的执行顺序_第1张图片

从上图可以得出的结论是:后添加的脚本先执行

4  设置脚本的执行顺序,点中其中的一个脚本,然后点击右上角的Execution Order...按钮,如下图:

设置unity脚本的执行顺序_第2张图片

在出现的面板中点击+号,选择要设置顺序的脚本,如下图:

设置unity脚本的执行顺序_第3张图片

设置Script1、Script2、Script3的Default Time值为100、200、300,注意Default Time值越小,越先执行,最后运行打印输出的结果如下图:

设置unity脚本的执行顺序_第4张图片

你可能感兴趣的:(unity)