Every time I load the menu scene, the Start and End gets called one extra time. So for every trigger press, it fires mutiple times.
Where can I put the intialization below, so that it only initializes once when the game first loads, and not every time I go back to the menu scene?
public InputActionReference trigger;
void Awake()
{
trigger.action.performed += Start;
trigger.action.canceled += End;
}
You are subscribing to the events but never unsubscribing, so you’ll continue to have the Start and End methods get called on each instance of your script even if you destroy the GameObject.
You can replace your Awake method in your script to this instead:
void OnEnable()
{
trigger.action.performed += Start; // Recommend renaming, see below.
trigger.action.canceled += End;
}
void OnDisable()
{
trigger.action.performed -= Start;
trigger.action.canceled -= End;
}
Note that your OnEnable will get called each time you re-enable your behavior, so it’s possible for it to happen more than once, but the OnDisable will get called when you disable or right before you destroy your behavior so it will even out.
You also named your callback method for performed Start
, which has special meaning in Unity. A method named Start in a MonoBehaviour gets automatically called once at startup if the behavior is enabled. So with your code, Start will be called once even if the action is not performed. I would recommend renaming your Start handler to something else instead.
You can call it inside OnDestroy() function as well.(same result no difference)
void OnDestroy()
{
trigger.action.performed -= Start;
trigger.action.canceled -= End;
}