WasTabon
WasTabon

Reputation: 143

How to pass parameters through the Initialize method of a MonoBehaviour class?

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:

  1. Check _playerMovement for null in FixedUpdate, but I'd rather avoid extra if statements in Update.
  2. Make Player without MonoBehaviour, but it's too long and there may be simpler ways.

Upvotes: 0

Views: 52

Answers (1)

DJ13423
DJ13423

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

Related Questions