The difference Awake between Start

I have learned InputSystem of Unity.
In my scripts

I create a function called"" attackTrigger()method"
and I use OnEnable, and call attackTrigger()methos with inputsystem

Finally I find that, if I have to do this scripts, I have to go back to top of script, and replace void Start() with void Awake()…

Does that mean""when using OnEnable(), I have to replace Start with Awake?

Here is my script;
void Awake() <------Why we don’t use Start?
{
ani = GetComponent();
playerInput = GetComponent();
attackaction = playerInput.actions[“Attack”];
}

private void OnEnable()
{
attackaction.performed += _ =>attackTrigger();
}
void attackTrigger()
{
ani.SetTrigger(“attack”);
}

Review this:

Your Awake() is always called before your OnEnable(), and both are called before the scene loader or caller’s Instantiate() even returns. Only after the execution gets to the main looping part, will your Start() get called, just before its first Update().

Thus, if you need to do any setup before OnEnable, you need to do it in Awake. If you want to do some setup stuff in Setup, that’s perfectly fine, but that will come after the caller has your gameObject reference and after the object has been enabled.

Regardless of this ordering, it’s a good idea to code defensively. If a member variable is null, don’t call methods using it. If you think it might change after the object was created, go ahead and attempt to update your null variable whenever you’re about to use it.

They all do different things and are used for different reasons. My rule of thumb: Self-initialisation in Awake; initialisation that depends on something else in Start. Can’t ever go wrong with that.

OnEnable/OnDisable is for when something should happen as the object is turned off/on (the .enabled property of components), something that I seldom ever use myself.

1 Like

Thanks for all of your explanations. Those explanations really help a lot