Reputation: 43
public class MovementControl : MonoBehaviour
{
[SerializeField] private GameObject playerToMove;
[SerializeField] private float speed = 5f;
private InputAction moveAction;
private float horizontal;
private float vertical;
public void Initialize(InputAction moveAction)
{
moveAction.Enable();
this.moveAction = moveAction;
}
private void OnEnable()
{
moveAction.Enable();
}
}
public class InputManager : MonoBehaviour
{
[SerializeField] private MovementControl movementController;
private InputActions inputScheme;
private void Awake()
{
inputScheme = new InputActions();
movementController.Initialize(inputScheme.Player.Move);
}
}
Unity reported that moveAction in OnEnable() was not set to a reference. Anyone has ideas on why OnEnable() is called before the completion of Awake()?
Upvotes: 4
Views: 5804
Reputation: 545
Unity doesn't go through all Awake() methods & 'then' all OnEnable() methods. Therefore, you would have cases where scripts executions order matters.
I logged Awake & OnEnable methods in both scripts, and the result was as following:
You could clearly see that Initialize method in MovementControl get executed way after OnEnable thus the null reference error.
What you could do is to change the order of execution of your scripts by going to Edit -> ProjectSettings and add InputManager then MovementControl to that list as following :
You could also add only InputManager to that list since that would automatically put it in front of all other scripts.
That being said, I would recommend that you make an architecture where you can centralize your Init methods with a minimum use of the execution order solution since it could get messy so fast!
Happy coding :)
Upvotes: 4
Reputation: 11
Unity does not know explicitly which Script runs after another but you can change that in: Script Execution Order settings
Upvotes: 1
Reputation:
I think Unity doesn't go through every Awake() first then every Enable(). The execution goes script by script rather every awake then every enable.
Is this in the same class? Try replacing the order of the 2 classes, otherwise I think their place in the object component hierarchy also affects this.
Upvotes: 0