前提
インターフェースの使い方を学習し始めたc#初心者です。
Googleで調べた通りにソースコードを書いてみましたが、敵側の処理が行われません。
どこがおかしいのか教えてくれると嬉しいです。
実現したいこと
敵との接触をインターフェースを用いて判断できるようにしたい。
sccharacterをもったキャラクターオブジェクトがscenemyをもった敵オブジェクトにぶつかったときにインターフェースをもとに敵かどうかを判断し処理を行いたい。
現在は簡略化のため敵オブジェクトを最初からキャラクターオブジェクトに取得させている。
発生している問題・エラーメッセージ
敵オブジェクトとぶつかった時にぶつかったことは確認できるが(consoleに ”collider” と表示される)、
敵側の処理を確認できない(consoleに "aaa" と表示されない)。
該当のソースコード
キャラクターオブジェクトのsccharacter.cs
C#
1using System.Collections; 2using System.Collections.Generic; 3using UnityEngine; 4 5public class sccharacter : MonoBehaviour 6{ 7 public GameObject kariene; 8 // Start is called before the first frame update 9 void Start() 10 { 11 12 } 13 14 // Update is called once per frame 15 void Update() 16 { 17 Vector3 vech = this.transform.position; 18 if (Input.GetKey(KeyCode.D)) 19 { 20 vech.x += 0.01f; 21 } 22 23 if (Input.GetKey(KeyCode.A)) 24 { 25 vech.x -= 0.01f; 26 } 27 28 if(Input.GetKey(KeyCode.S)) 29 { 30 var attack = kariene.GetComponent<Ienemy>(); 31 if (attack != null) 32 { 33 Debug.Log("aaa"); 34 attack.fxenemy(); 35 } 36 } 37 38 this.transform.position = vech; 39 } 40 41// 敵オブジェクトとぶつかったときの処理 42 43 private void OnCollisionEnter2D(Collision2D collision) 44 { 45 Debug.Log("collider"); 46 var attack = collision.gameObject.GetComponent<Ienemy>(); 47 if(attack != null) 48 { 49 Debug.Log("aaa"); 50 attack.fxenemy(); 51 } 52 } 53} 54
インターフェースのIenemy.cs
C#
1using System.Collections; 2using System.Collections.Generic; 3using UnityEngine; 4 5// インターフェース 6 7public interface Ienemy 8{ 9 void fxenemy(); 10}
敵オブジェクトのscenemy.cs
C#
1using System.Collections; 2using System.Collections.Generic; 3using UnityEngine; 4 5public class scenemy : MonoBehaviour 6{ 7 // Start is called before the first frame update 8 void Start() 9 { 10 11 } 12 13 // Update is called once per frame 14 void Update() 15 { 16 17 } 18} 19 20// 敵側の処理 21public class cenemy : MonoBehaviour,Ienemy 22{ 23 public void fxenemy() 24 { 25 Debug.Log("enemy"); 26 } 27}
試したこと
sccharacterの 敵オブジェクトとぶつかった時の処理 のGetComponentの部分を
GetComponent(typeof(Ienemy)) as Ienemy
にしてみたが変化はなかった
補足情報
visualstudio2022
回答1件