Execution order within the Update() loop method in

2019-05-24 18:16发布

I'm trying to find the appropriate words to use to describe the issue that I am having, hopefully this will explain the problem.

I have two Update() methods in two different classes, and some of the functionality in one is reliant on data from another. Code A is reliant on Code B's data, using Debug.Log() I found that Code B's Update() is being executed after Code A's Update().

My question is, Is there a out of box method to controller the Call stack of the Update method? If there is how is it done? If there isn't, does anyone have any technique that I could employ to resolve the problem. I realize I could just create methods in Code B that could be called from Code A in update to resolve the problem, but I'm curious to see if there is another way to resolve the problem.

3条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-05-24 18:20

A basic mechanism could be represented by locks.

As an example, let's suppose that A's block depends on B's one. You can control the "dependency" this way:

//B script:
var BLogicPerformed = false;

//...
//Code on which A depends:
function Update(){
    if (BLogicPerformed == false){
        //your operations...
        BLogicPerformed = true;
    }
}

//------------------------------------------------
//A script:

//...
//Code that depends on B:
 function Update(){
    if (this.GetComponent("B").BLogicPerformed == true){
        //Perform logic that depends on B
        this.GetComponent("B").BLogicPerformed = false;
    }
 }

(ugly comparisons with boolean values where just made to keep the code as much clear as I could :-))

I program in Unityscript and, since your question is tagged with both and , I hope that's sufficient for you.

查看更多
家丑人穷心不美
3楼-- · 2019-05-24 18:23

if its only oneway you could use LateUpdate() instead of Update() in one of the scripts

查看更多
\"骚年 ilove
4楼-- · 2019-05-24 18:28

From Unity's reference manual:

By default, the Awake, OnEnable and Update functions of different scripts are called in the order the scripts are loaded (which is arbitrary). However, it is possible to modify this order using the Script Execution Order settings.

That should solve your problem.

查看更多
登录 后发表回答