How to implement "PreUpdate" function

Hi,

I need to have a function in MonoBehaviour that is called before any Update functions of any other objects. LateUpdate is called after Update function and I would need something like "PreUpdate" that is called before.

Note: FixedUpdate will not work because on very short frames it may be not called at all.

Thanks in advance.

In general, it’s helpful to explain the problem you are trying to solve, rather than the technical limitation that you believe prevents its solution. (Is there a reason, for example, that this couldn’t be calculated in LateUpdate of the previous frame?)

However, it sounds like what you’re trying to achieve could be done by placing all your “pre-update” logic in the Update() function of a new script, and setting that script to execute before all others:

While tanoshimi’s answer does seem to give the simplest way to achieve a "PreUpdate" using FixedUpdate (see the second link), there is a possibility FixedUpdate will not get called before each and every update only one time. I will propose a simple system which guarantees that a method is called before any logic in any Update is called. The solution relies heavily on the Script execution order of Unity, as suggested by iwaldrop.

You will need this script in a GameObject in every scene you require the PreUpdate. I recommend creating a prefab.

using UnityEngine;
using System.Collections;
  
public class FirstScript : MonoBehaviour {
  
	public static event System.Action PreUpdate;
  
	// Update is called once per frame
	void Update () {
		if(PreUpdate != null)
			PreUpdate();
	}
}

You will then need to set this script to be executed first. Open the Script Execution Order inspector, drag this script there and set it to execute first (above default time).

Then, in whichever script you require a PreUpdate function, just subscribe to the PreUpdate event in FirstScript. For example:

using UnityEngine;
using System.Collections;
  
public class NewBehaviourScript : MonoBehaviour {
  
	void OnEnable () {
		FirstScript.PreUpdate += HandlePreUpdate;
	}
  
	void HandlePreUpdate ()
	{
		Debug.Log("Preupdate in "+this.ToString() +" "+Time.frameCount);
	}
  
	void Update () {
		Debug.Log("Update "+this.ToString() +" "+Time.frameCount);
	}
	void OnDisable(){
		FirstScript.PreUpdate -= HandlePreUpdate;
	}
}

HandlePreUpdate will always be called before any logic in any Update (except in FirstScript) is run.

If you require absolute control as to which PreUpdate is called first, you will have to modify FirstScript such that it maintains a List of functions which it calls, in order, from its Update.

I know this is a very old thread, but after failing to successfully implement any of the other solutions here (my problem wasn’t compatible with any of them) I implemented this, and it works well for my purpose. I wanted to capture control info to make rebinding easier, and to get away from Unity’s string-based key identifiers. It’s not perfect for everyone, but it fits my use-case.

public class PlayerInput : MonoBehaviour
{
    int lastCheckedFrame = -1;
    InputState state;
    public InputState State 
    { get{ 
        if( lastCheckedFrame != Time.frameCount )
        {
            state = new InputState();
            lastCheckedFrame = Time.frameCount;
        } 
        return state;
    } }
}
  
public class InputState
{
    float thrust = 0;
    float roll = 0;
    float pitch = 0;
    float yaw = 0;
  
    public InputState()
    {
        // Turn Input.GetAxis into variables here
    }
}

LateUpdate does get executed before any Update functions of any other objects on the next tick.

Let’s see an actual example:

while(true) {
    for(var CurrentObject in AllObjects) {
        CurrentObject.Update()
        CurrentObject.LateUpdate();
    }
}

If you add an EarlyUpdate function, there is not going to be any difference between an EarlyUpdate and a LateUpdate from the perspective of the Update function on all ticks, except for the first one:

while(true) {
    for(var CurrentObject in AllObjects) {
        CurrentObject.EarlyUpdate();
        CurrentObject.Update()
        CurrentObject.LateUpdate();
    }
}

And to execute things early before the first update, just use use Start or Awake and execute your early update there.

While it works most of the time, here’s a way to actually implement the super early and super late updates, exactly what you want:

Well, I think the reason the PreUpdate method isn’t defined in Unity is because it isn’t needed.
My belief is that there is always a workaround.

If you absolutely want to change the state of your game before everything else, you can declare a function instead of all those Updates() that will be called by your StateMachine AFTER it has Updated its State.

First define a parent for all the objects that depends on the StateMachine

using UnityEngine;
using System.Collections;

// Parent for all objects that uses the StateMachine
// Mostly to be able to store all these scripts in a List<MyParentClass> variable
public abstract class ParentClass : MonoBehaviour
{
	public abstract void ApplyConsequences();
}

Then use the parent classes on all your Objects that depends on the StateMachine.

using UnityEngine;
using System.Collections;

public class AnObject : ParentClass
{
	void Awake()
	{
		// There you should add yourself in the memory of the StateMachine 
		// so it could then call all your ApplyStateMachineBehaviour() functions

		MyStateMachine.Instance.MyObjects.Add(this);

		// You might want to put the Awake in the parent instead, but not sure if it'll work.
		// If you do be sure to remove abstract from ParentClass since you define a function.
	}

	public override void ApplyConsequences()
	{
		// There you define your desired effects
	}
}

Finally use the defined function after you Update your StateMachine

public class MyStateMachine : MonoBehaviour
{
	// A trick to be able to easily access one script from other scripts
	// ===========================================
	private static MyStateMachine instance;

	void Awake()
	{
		instance = this;
	}

	public static MyStateMachine Instance
	{
		get{return instance;}
	}
	// ===========================================

	private List<ParentClass> myObjects = new List<ParentClass>();

	public List<ParentClass> MyObjects
	{
		get{return myObjects;}
	}

	void Update () 
	{
		UpdateState();
		ApplyAllConsequences();
	}

	// There you Update your State
	void UpdateState()
	{
		// ...
		// ...
		// ...
	}

	// There you call ALL ApplyConsequences()
	void ApplyAllConsequences()
	{
		foreach(ParentClass obj in myObjects)
		{
			obj.ApplyConsequences();
		}
	}
}

Be warned that you will surely have to use the LateUpdate function since all Updates from all objects are processed simultaneously.

If your stuck in the LateUpdate, try to use a similar trick to order your functions properly. Define functions, and call the after another function.