UnityとC#の単一責任の原則の学習教材に於ける正しい適用方法がわからない

前提

UnityとC#の勉強をしています。
Githubにある、ゲーム開発におけるデザインパターンの学習教材で単一責任の原則を学ぼうと思ったのですが、
単一責任を適用したスクリプトの動作方法がわからず困っています。

実現したいこと

発生している問題・エラーメッセージ

元コードの場合はオブジェクトにアタッチすることでオブジェクトが移動するのですが、 そのコードに単一責任の原則を適用したコードの場合は、オブジェクトにアタッチするだけではオブジェクトを動かせない。

該当のソースコード

元のコード

C#

namespace DesignPatterns.SRP { // Even though this class is short, it violates single-responsibility. // Too many things will cause the class to update, and extending the class will be more difficult. public class UnrefactoredPlayer : MonoBehaviour { [SerializeField] private string _inputAxisName; [SerializeField] private float _positionMultiplier; private float _yPosition; private AudioSource _bounceSfx; private void Start() { _bounceSfx = GetComponent<AudioSource>(); } private void Update() { float delta = Input.GetAxis(_inputAxisName) * Time.deltaTime; _yPosition = Mathf.Clamp(_yPosition + delta, -1, 1); transform.position = new Vector3(transform.position.x, _yPosition * _positionMultiplier, transform.position.z); } private void OnTriggerEnter(Collider other) { _bounceSfx.Play(); } } }

適用したコード

C#

namespace DesignPatterns.SRP { [RequireComponent(typeof(PlayerAudio), typeof(PlayerInput), typeof(PlayerMovement))] public class Player : MonoBehaviour { [SerializeField] private PlayerAudio playerAudio; [SerializeField] private PlayerInput playerInput; [SerializeField] private PlayerMovement playerMovement; private void Start() { playerAudio = GetComponent<PlayerAudio>(); playerInput = GetComponent<PlayerInput>(); playerMovement = GetComponent<PlayerMovement>(); } }}

C#

namespace DesignPatterns.SRP { // sample code to demo single-responsibility: public class PlayerInput : MonoBehaviour { [SerializeField] private string inputAxisName; private void Update() { float delta = Input.GetAxis(inputAxisName) * Time.deltaTime; } }}

C#

namespace DesignPatterns.SRP { // sample code to demo single-responsibility public class PlayerMovement : MonoBehaviour { [SerializeField] private float positionMultiplier; private float yPosition; private void Update() { transform.position = new Vector3(transform.position.x, yPosition * positionMultiplier, transform.position.z); yPosition++; } }}

試したこと

unity内にてinputAxisNameを設定した。
PlayerでplayerInputを使って入力を受け取り、playerMovementのyPositionに代入して動かそうと思ったが、
yPositionがprivateのため、その動かし方は想定してないと判断。

補足情報(FW/ツールのバージョンなど)

Unity 2021.3.11f1
VisualStudio 2022 17.3.5

コメントを投稿

0 コメント