64 lines
1.9 KiB
C#
64 lines
1.9 KiB
C#
using Solid.Interfaces;
|
|
using UnityEngine;
|
|
using UnityEngine.Assertions;
|
|
|
|
namespace Solid
|
|
{
|
|
[RequireComponent(typeof(PlayerInput), typeof(PlayerMovement))]
|
|
public class PlayerController : MonoBehaviour
|
|
{
|
|
private IInput _playerInput;
|
|
private PlayerMovement _playerMovement;
|
|
private IShooter _shooter;
|
|
|
|
// BAD IDEA
|
|
// [SerializeField] private bool _isUsingGamepad = false;
|
|
|
|
private void Awake()
|
|
{
|
|
// BAD IDEA
|
|
// don't use concrete classes, use abstraction instead, e.g. IInput interface
|
|
// don't instantiate concrete classes, use dependency injection instead => use services
|
|
// if (_isUsingGamepad)
|
|
// {
|
|
// _playerInput = new GamepadInput();
|
|
// }
|
|
// else
|
|
// {
|
|
// _playerInput = new KeyboardMouseInput();
|
|
// }
|
|
|
|
_playerInput = GetComponent<IInput>();
|
|
_playerMovement = GetComponent<PlayerMovement>();
|
|
|
|
// _shooter = GetComponent<IShooter>() ?? gameObject.AddComponent<BulletShooter>(); // default option, not so good
|
|
|
|
// better solution
|
|
_shooter = GetComponent<IShooter>();
|
|
Assert.IsNotNull(_shooter, "No IShooter component found on the GameObject.");
|
|
|
|
// best solution will be again to use dependency injection
|
|
}
|
|
|
|
private void OnEnable()
|
|
{
|
|
_playerInput.Fired += OnFired;
|
|
}
|
|
|
|
private void OnDisable()
|
|
{
|
|
_playerInput.Fired -= OnFired;
|
|
}
|
|
|
|
private void OnFired()
|
|
{
|
|
_shooter.Fire();
|
|
}
|
|
|
|
private void Update()
|
|
{
|
|
_playerInput.HandleInput();
|
|
_playerMovement.MoveAndRotate(_playerInput.Movement, _playerInput.Rotation);
|
|
}
|
|
}
|
|
} |