(スクリプト1:呼び出されるコルーチンのコードを記述)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Gift : MonoBehaviour
{
public GameObject giftPrefab;
// アクセス修飾子は「public」にすること(重要)
public IEnumerator Present()
{
for(int i = 0; i < 10; i++)
{
Instantiate(giftPrefab, transform.position, Quaternion.identity);
yield return new WaitForSeconds(1.0f);
}
}
}
(スクリプト2:コルーチンを作動させるコードを記述)
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class HumanHP : MonoBehaviour
{
public GameObject effectPrefab;
public AudioClip sound;
private int MaxHP = 3;
private int HP;
public Slider HPSlider;
private GameObject[] targets;
public GameObject effectPrefad2;
// ★追加
public GameObject gift;
private void Start()
{
HP = MaxHP;
HPSlider.maxValue = MaxHP;
HPSlider.value = HP;
}
void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.CompareTag("toge"))
{
GameObject effect = Instantiate(effectPrefab, collision.transform.transform.position, Quaternion.identity);
Destroy(effect, 1.0f);
AudioSource.PlayClipAtPoint(sound, Camera.main.transform.position);
HP -= 1;
HPSlider.value = HP;
if (HP == 0)
{
targets = GameObject.FindGameObjectsWithTag("Hana");
foreach(GameObject i in targets)
{
Destroy(i);
GameObject effect2 = Instantiate(effectPrefad2, i.transform.position, Quaternion.identity);
Destroy(effect2, 3.0f);
}
Destroy(transform.root.gameObject);
// ★追加
// 別スクリプト内のコルーチンを作動させる。
// 「名前」呼び出しなので、一言一句正確に記述する。
gift.GetComponent<Gift>().StartCoroutine("Present");
}
}
}
}