In many games we have some UI which is used to control the player character. Typically we write some InputManager script which detects UI interactions and we also write some Player script which has the logic to react to those interactions.
But how exactly should I connect my InputManager and my Player scripts? I want to avoid code coupling.
Here is an example:
In my InputManager.cs script I have the following method:
public void JumpBtnClicked()
{
GameObject playerObject = GameObject.FindGameObjectWithTag(“Player”);
Player playerScript = playerObject.GetComponent();
playerScript.Jump();
}
Every time the jump button is clicked, the InputManager calls playerScript.Jump() method. But this way my InputManager and Player scripts are tightly coupled. I want to create a layer of abstraction between my InputManager and my Player script. I am thinking about writing an event system and then generating events every time some UI button is clicked. Then my player script could subscribe to those events. But I’m not sure where exactly I must write the code that subrscibes my player to the jump event. Is this even a good appraoch overall? Maybe you could suggest a better design.
Any help will be greatly appreciated! Thank you!