ブログ

画面上の敵を全て破壊するコード(foreachの活用)

(スクリプト)

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class DestroyAllEnemy : MonoBehaviour
{
    private GameObject[] targets;
    public GameObject effectPrefab;

    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        if(Input.GetKeyDown(KeyCode.Space))
        {
            targets = GameObject.FindGameObjectsWithTag("Enemy");

            foreach(GameObject e in targets)
            {
                Destroy(e);

                GameObject effect = Instantiate(effectPrefab, e.transform.position, Quaternion.identity);
                Destroy(effect, 0.5f);

            }
        }
    }
}