Krucho
Krucho

Reputation: 117

Simulating Update() call on MonoBehaviour

How can I call Update() or Start() or any other MonoBehaviour method directly?

I disabled most of my MonoBehaviour auto Update() calls by setting enabled = false; on each of them, because I need to time Update() at a very specific time for those scripts.

I am thinking about doing it like this:

List<MonoBehaviour> disabledScripts;
foreach (MonoBehaviour m in disabledScripts)
    m.Update();

But i'm not sure if it is the correct way to do it since not all MonoBehaviour in disabledScripts actually implement Update().

Upvotes: 1

Views: 1779

Answers (2)

Krucho
Krucho

Reputation: 117

Alright I figured it out:

script.Update();

compiles an error, the correct way to do it is:

script.SendMessage("Update");

I also found out that setting enabled = false; also disables some other methods such as Start(), so I think I'll just extend MonoBehaviour and move all Update() code to MyUpdate() as antonio said.

Upvotes: 1

antonio
antonio

Reputation: 18242

Start is called automatically on object start and Update is called automatically on each frame by the engine.

If you want to control the order in which the scripts's Start() or Update() method is called take a look at this http://docs.unity3d.com/Manual/class-ScriptExecution.html

If you need to execute certain code in a controlled timing or need on certain conditions, better create an specific method for each object and create a controller to call this method on each object at the desired time.

For example you can leave Update() method empty for every object and create a method called MyUpdate (with parameters if you wish) and call it when needed from the controller based on your game's workflow.

Unity's base flow must be kept unaltered, because it can lead to strange behaviors. I can't think about a thing that can't be done with Unity's natural flow.

Edit: Ok, I understand that you don't want to create a complex functionality just to try something.

As you say, disabling the behaviour forces the engine to avoid calling Update on each frame for the given MonoBehaviour, but I don't think you can call Update as you propose because in MonoBehaviour, Update has no method modifiers (see method without access modifier)

Anyway, I would create a "MyMonoBehaviour" extending MonoBehaviour with a MyUpdate() function that you will override on each object extending MyMonoBehaviour. You can call the MyUpdate function doing something like this (very similar to the code you proposed):

List<MyMonoBehaviour> disabledScripts;
foreach (MyMonoBehaviour m in disabledScripts)
    m.MyUpdate();

Upvotes: 1

Related Questions