複数の敵の攻撃を一定時間止める

複数の敵の攻撃を一定時間止める
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class StopAttack : MonoBehaviour {
private GameObject[] targets1;
private GameObject[] targets2;
private float timeCount;
void Update(){
// (ポイント)
// Update内に記載することで、途中で敵の数が増えても対応できるようになる。
targets1 = GameObject.FindGameObjectsWithTag ("EnemyShotShell");
print (targets1.Length);
timeCount += Time.deltaTime;
print (timeCount);
}
void OnTriggerEnter(Collider other){
if (other.gameObject.tag == "Shell") {
timeCount = 0;
this.gameObject.SetActive (false);
Destroy (other.gameObject);
// (ポイント)「foreach」の使い方を学習しましょう。
foreach (GameObject targetGameObject in targets1) {
// 敵のEnemyShotShellコンポーネント(スクリプト)をオフにする。
targetGameObject.GetComponent<EnemyShotShell> ().enabled = false;
}
// (比較してみましょう!)
// 「for」を使った書き方は以下の通りです。
/*
for (int i = 0; i < targets.Length; i++) {
targetGameObject.GetComponent<EnemyShotShell> ().enabled = false;
}
*/
// 4秒後に敵の攻撃を復活させる。
Invoke ("RestartAttack", 4.0f);
}
}
void RestartAttack(){
// (重要ポイント)
// 4秒後にもう一度、敵のオブジェクトを探し直す。
// これを行わないと、「4秒の間に倒した敵」がいる場合、倒した敵のデータが「Missing(見失った)」となり攻撃回復がうまくいかなくなる。
targets2 = GameObject.FindGameObjectsWithTag ("EnemyShotShell");
foreach (GameObject targetGameObject in targets2) {
targetGameObject.GetComponent<EnemyShotShell> ().enabled = true;
}
}
}


Unity Code Memo
他のコースを見る
複数の敵の攻撃を一定時間止める
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class StopAttack : MonoBehaviour {
private GameObject[] targets1;
private GameObject[] targets2;
private float timeCount;
void Update(){
// (ポイント)
// Update内に記載することで、途中で敵の数が増えても対応できるようになる。
targets1 = GameObject.FindGameObjectsWithTag ("EnemyShotShell");
print (targets1.Length);
timeCount += Time.deltaTime;
print (timeCount);
}
void OnTriggerEnter(Collider other){
if (other.gameObject.tag == "Shell") {
timeCount = 0;
this.gameObject.SetActive (false);
Destroy (other.gameObject);
// (ポイント)「foreach」の使い方を学習しましょう。
foreach (GameObject targetGameObject in targets1) {
// 敵のEnemyShotShellコンポーネント(スクリプト)をオフにする。
targetGameObject.GetComponent<EnemyShotShell> ().enabled = false;
}
// (比較してみましょう!)
// 「for」を使った書き方は以下の通りです。
/*
for (int i = 0; i < targets.Length; i++) {
targetGameObject.GetComponent<EnemyShotShell> ().enabled = false;
}
*/
// 4秒後に敵の攻撃を復活させる。
Invoke ("RestartAttack", 4.0f);
}
}
void RestartAttack(){
// (重要ポイント)
// 4秒後にもう一度、敵のオブジェクトを探し直す。
// これを行わないと、「4秒の間に倒した敵」がいる場合、倒した敵のデータが「Missing(見失った)」となり攻撃回復がうまくいかなくなる。
targets2 = GameObject.FindGameObjectsWithTag ("EnemyShotShell");
foreach (GameObject targetGameObject in targets2) {
targetGameObject.GetComponent<EnemyShotShell> ().enabled = true;
}
}
}


複数の敵の攻撃を一定時間止める