プレーヤーのステータス③(残機数を画面に表示する)
















プレーヤーの残機アイコンの表示
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class PlayerHealth : MonoBehaviour
{
public GameObject effectPrefab;
public AudioClip damageSound;
public AudioClip destroySound;
public int playerHP;
public Slider hpSlider;
// ★(追加)
// 配列の定義(「複数のデータ」を入れることのできる「仕切り」付きの箱を作る)
public GameObject[] playerIcons;
// ★(追加)
// プレーヤーが破壊された回数のデータを入れる箱
private int destroyCount = 0;
private void Start()
{
hpSlider.maxValue = playerHP;
hpSlider.value = playerHP;
}
private void OnTriggerEnter(Collider other)
{
if(other.gameObject.CompareTag("EnemyMissile"))
{
playerHP -= 1;
AudioSource.PlayClipAtPoint(damageSound, Camera.main.transform.position);
Destroy(other.gameObject);
hpSlider.value = playerHP;
if (playerHP == 0)
{
GameObject effect = Instantiate(effectPrefab, transform.position, Quaternion.identity);
Destroy(effect, 1.0f);
AudioSource.PlayClipAtPoint(destroySound, Camera.main.transform.position);
this.gameObject.SetActive(false);
// ★(追加)
// HPが0になったら破壊された回数を1つ増加させる。
destroyCount += 1;
// ★(追加)
// 命令ブロック(メソッド)を呼び出す。
UpdatePlayerIcons();
}
}
}
// ★(追加)
// プレーヤーの残機数を表示する命令ブロック(メソッド)
void UpdatePlayerIcons()
{
// for文(繰り返し文)・・・まずは基本形を覚えましょう!
for (int i = 0; i < playerIcons.Length; i++)
{
if(destroyCount <= i)
{
playerIcons[i].SetActive(true);
}
else
{
playerIcons[i].SetActive(false);
}
}
}
}



【2019版】Danmaku I(基礎1/全22回)
他のコースを見る















プレーヤーの残機アイコンの表示
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class PlayerHealth : MonoBehaviour
{
public GameObject effectPrefab;
public AudioClip damageSound;
public AudioClip destroySound;
public int playerHP;
public Slider hpSlider;
// ★(追加)
// 配列の定義(「複数のデータ」を入れることのできる「仕切り」付きの箱を作る)
public GameObject[] playerIcons;
// ★(追加)
// プレーヤーが破壊された回数のデータを入れる箱
private int destroyCount = 0;
private void Start()
{
hpSlider.maxValue = playerHP;
hpSlider.value = playerHP;
}
private void OnTriggerEnter(Collider other)
{
if(other.gameObject.CompareTag("EnemyMissile"))
{
playerHP -= 1;
AudioSource.PlayClipAtPoint(damageSound, Camera.main.transform.position);
Destroy(other.gameObject);
hpSlider.value = playerHP;
if (playerHP == 0)
{
GameObject effect = Instantiate(effectPrefab, transform.position, Quaternion.identity);
Destroy(effect, 1.0f);
AudioSource.PlayClipAtPoint(destroySound, Camera.main.transform.position);
this.gameObject.SetActive(false);
// ★(追加)
// HPが0になったら破壊された回数を1つ増加させる。
destroyCount += 1;
// ★(追加)
// 命令ブロック(メソッド)を呼び出す。
UpdatePlayerIcons();
}
}
}
// ★(追加)
// プレーヤーの残機数を表示する命令ブロック(メソッド)
void UpdatePlayerIcons()
{
// for文(繰り返し文)・・・まずは基本形を覚えましょう!
for (int i = 0; i < playerIcons.Length; i++)
{
if(destroyCount <= i)
{
playerIcons[i].SetActive(true);
}
else
{
playerIcons[i].SetActive(false);
}
}
}
}



プレーヤーのステータス③(残機数を画面に表示する)