前提
UnityとC#の勉強をしています。
Githubにある、ゲーム開発におけるデザインパターンの学習教材で単一責任の原則を学ぼうと思ったのですが、
単一責任を適用したスクリプトの動作方法がわからず困っています。
実現したいこと
- 単一責任の原則を適用したコードを動かしたい
発生している問題・エラーメッセージ
元コードの場合はオブジェクトにアタッチすることでオブジェクトが移動するのですが、 そのコードに単一責任の原則を適用したコードの場合は、オブジェクトにアタッチするだけではオブジェクトを動かせない。
該当のソースコード
元のコード
C#
1namespace DesignPatterns.SRP 2{ 3 // Even though this class is short, it violates single-responsibility. 4 // Too many things will cause the class to update, and extending the class will be more difficult. 5 6 public class UnrefactoredPlayer : MonoBehaviour 7 { 8 9 [SerializeField] private string _inputAxisName; 10 11 [SerializeField] private float _positionMultiplier; 12 13 private float _yPosition; 14 15 private AudioSource _bounceSfx; 16 17 private void Start() 18 { 19 _bounceSfx = GetComponent<AudioSource>(); 20 } 21 22 private void Update() 23 { 24 float delta = Input.GetAxis(_inputAxisName) * Time.deltaTime; 25 26 _yPosition = Mathf.Clamp(_yPosition + delta, -1, 1); 27 28 transform.position = new Vector3(transform.position.x, _yPosition * _positionMultiplier, transform.position.z); 29 } 30 31 private void OnTriggerEnter(Collider other) 32 { 33 _bounceSfx.Play(); 34 } 35 } 36 37}
適用したコード
C#
1namespace DesignPatterns.SRP 2{ 3 [RequireComponent(typeof(PlayerAudio), typeof(PlayerInput), typeof(PlayerMovement))] 4 public class Player : MonoBehaviour 5 { 6 [SerializeField] private PlayerAudio playerAudio; 7 [SerializeField] private PlayerInput playerInput; 8 [SerializeField] private PlayerMovement playerMovement; 9 10 private void Start() 11 { 12 playerAudio = GetComponent<PlayerAudio>(); 13 playerInput = GetComponent<PlayerInput>(); 14 playerMovement = GetComponent<PlayerMovement>(); 15 } 16 17 } 18}
C#
1namespace DesignPatterns.SRP 2{ 3 // sample code to demo single-responsibility: 4 public class PlayerInput : MonoBehaviour 5 { 6 [SerializeField] private string inputAxisName; 7 8 private void Update() 9 { 10 float delta = Input.GetAxis(inputAxisName) * Time.deltaTime; 11 } 12 } 13} 14
C#
1namespace DesignPatterns.SRP 2{ 3 // sample code to demo single-responsibility 4 public class PlayerMovement : MonoBehaviour 5 { 6 [SerializeField] private float positionMultiplier; 7 private float yPosition; 8 9 private void Update() 10 { 11 transform.position = new Vector3(transform.position.x, yPosition * positionMultiplier, transform.position.z); 12 yPosition++; 13 } 14 } 15}
試したこと
unity内にてinputAxisNameを設定した。
PlayerでplayerInputを使って入力を受け取り、playerMovementのyPositionに代入して動かそうと思ったが、
yPositionがprivateのため、その動かし方は想定してないと判断。
補足情報(FW/ツールのバージョンなど)
Unity 2021.3.11f1
VisualStudio 2022 17.3.5

回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2022/10/17 12:01