前提・実現したいこと・発生した問題
unityでFPSゲームを作っている中で、銃で敵を撃ってrayが当たったらその攻撃を受けた敵のHPを1減らし、その敵のHPが0になったらその敵オブジェクトを破壊するというシステムを作っています。
現在敵をステージに3体設置してテストをしているのですが、そのうちの1体に一度rayを当てると全ての敵のHPが1減ってしまいます。これをそのrayが当たった敵1体だけにダメージが入るようにしたいです。(例 現在の状態では、ある敵一体だけに弾をあてると、3体の敵のHPは、2→1 2→1 2→1 これを、 2→1 2のまま 2のまま になるようにしたい。)
敵は、capsuleにソースコード"EnemyController"が貼ってあり、tagを"Enemy"にしたオブジェクトで、prefab化した状態でステージに3体設置しています。
unity初心者です。よろしくお願いします。
該当のソースコード
EnemyControllerとPlayer(←一応)を貼っておきます。
c#
1 /* EnemyController */ 2 3using System.Collections; 4using System.Collections.Generic; 5using UnityEngine; 6 7public class EnemyController : MonoBehaviour 8{ 9 10 [SerializeField] private int hp = 2; 11 GameObject playerr; 12 void Start() 13 { 14 playerr = GameObject.Find("FPSController"); 15 } 16 17 void Update() 18 { 19 20 if (Input.GetMouseButtonDown(0)) 21 { 22 if(playerr.GetComponent<Player>().hit.collider.tag == "Enemy") 23 { 24 this.hp--; 25 if(this.hp == 0) 26 { 27 Destroy(playerr.GetComponent<Player>().hit.collider.gameObject); 28 } 29 } 30 31 } 32 33 } 34}
c#
1 /*Player*/ 2 3using System.Collections; 4using System.Collections.Generic; 5using UnityEngine; 6 7// FPSController 8 9public class Player : MonoBehaviour 10{ 11 Vector3 point; 12 public Camera cam; 13 //光線を飛ばすためにはカメラが必要 14 15 public bool rayHit; 16 GameObject gun_snd; 17 GameObject score_UI; 18 public RaycastHit hit; 19 20 void Start() 21 { 22 gun_snd = GameObject.Find("Ak-47"); 23 score_UI = GameObject.Find("score_text"); 24 } 25 26 27 void Update() 28 { 29 Ray ray = cam.ViewportPointToRay(new Vector3(0.5f, 0.5f, 0)); 30 //ray..光線を生成 ViewportPointToRay..ビユーポート座標をrayに変換 31 Debug.DrawRay(ray.origin, ray.direction); 32 33 34 if(Physics.Raycast(ray, out hit)) 35 //out hit.. ぶつかったオブジェクトの情報 36 { 37 rayHit = true; 38 39 40 } 41 else 42 { 43 rayHit = false; 44 } 45 46 47 48 //残弾処理 49 if (Input.GetMouseButtonDown(0) && gun_snd.GetComponent<gun_Sound>().canShoot ) 50 { 51 score_UI.GetComponent<ScoreController>().nokori_tama_cnt--; 52 Debug.Log(hit.point); 53 54 55 56 } 57 if(score_UI.GetComponent<ScoreController>().nokori_tama_cnt == 0) 58 { 59 gun_snd.GetComponent<gun_Sound>().canShoot = false; 60 } 61 if (Input.GetKeyDown(KeyCode.R)) 62 { 63 score_UI.GetComponent<ScoreController>().nokori_tama_cnt = 30; 64 gun_snd.GetComponent<gun_Sound>().canShoot = true; 65 } 66 } 67} 68
試したこと
EnemyControllerのthis.hpをhpにしましたがだめでした。
EnemyControllerの[SerializeField] privateの部分をpublicにしましたがダメでした。
補足情報(ツールのバージョンなど)
unityのバージョン: Unity 2018.4.0f1
回答3件
あなたの回答
tips
プレビュー