(スクリプト)
*コルーチンを変数化するのがポイント
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyShotShell : MonoBehaviour
{
public GameObject enemyShellPrefab;
public AudioClip sound;
// ★コルーチンの変数化(ポイント)
private IEnumerator shotX;
void Start()
{
shotX = Shot();
StartCoroutine(shotX);
}
private void Update()
{
if(Input.GetKeyDown(KeyCode.J))
{
StopCoroutine(shotX);
}
if(Input.GetKeyDown(KeyCode.L))
{
StartCoroutine(shotX);
}
}
private IEnumerator Shot()
{
yield return new WaitForSeconds(1f);
while (true)
{
GameObject enemyShell = Instantiate(enemyShellPrefab, transform.position, Quaternion.identity);
Rigidbody enemyShellRb = enemyShell.GetComponent<Rigidbody>();
enemyShellRb.AddForce(transform.forward * 300);
AudioSource.PlayClipAtPoint(sound, transform.position);
Destroy(enemyShell, 5.0f);
yield return new WaitForSeconds(1f);
}
}
}
(実行結果)
*Jキー押しで、敵の攻撃が停止
*Lキー押しで、敵の攻撃が再開