Reputation: 143
public class Player : MonoBehaviour
{
public void Initialize(Vector3 spawnPosition, InputManager inputManager)
{
_playerMovement = new PlayerMovement(_inputManager, _rigidbody, _wheels);
}
private void FixedUpdate()
{
_playerMovement.Method();
}
}
I want to make it possible to create a player in Bootstrap and immediately pass parameters to it (Vector3 spawnPosition, InputManager inputManager).
The problem is that I need to Instantiate it first and then call Initialize, but during this time FixedUpdate may be called, which will try to access null _playerMovement, causing errors.
There are 2 ways to solve this problem:
Upvotes: 0
Views: 52
Reputation: 105
As far as I know theres no other way to do it except for checking if _playerMovement
null.
This is an easy way to do a null check without having to put an if statement in your FixedUpdate
.
private void FixedUpdate()
{
_playerMovement?.Method();
}
And if you don't like that way you could also call the method in another function.
private void PlayerMovementMethod()
{
if (_playerMovement != null)
_playerMovement.Method();
// or you can use:
// _playerMovement?.Method();
}
private void FixedUpdate()
{
PlayerMovementMethod();
}
Upvotes: 1