敵オブジェクトの作成
敵からダメージを受ける
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class PlayerHP : MonoBehaviour
{
public AudioClip damageSound;
private Animator animator;
private int HP;
private int maxHP = 3;
public GameObject[] hpIcons;
public AudioClip dieSound;
private void Start()
{
animator = GetComponent<Animator>();
HP = maxHP;
}
private void OnCollisionEnter2D(Collision2D collision)
{
// ★追加(敵からダメージ)
if (collision.gameObject.CompareTag("Trap") || collision.gameObject.CompareTag("Enemy")) // 条件の追加
{
HP -= 1;
HPIconManager();
animator.SetTrigger("Damage");
if (HP > 0)
{
AudioSource.PlayClipAtPoint(damageSound, transform.position);
}
else
{
AudioSource.PlayClipAtPoint(dieSound, transform.position);
Invoke("Restart", 0.15f);
}
}
}
void HPIconManager()
{
for (int i = 0; i < hpIcons.Length; i++)
{
if (i < HP)
{
hpIcons[i].SetActive(true);
}
else
{
hpIcons[i].SetActive(false);
}
}
}
void Restart()
{
SceneManager.LoadScene("Main");
}
}
【2022版】ActionGame2D(全33回)
他のコースを見る敵からダメージを受ける
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class PlayerHP : MonoBehaviour
{
public AudioClip damageSound;
private Animator animator;
private int HP;
private int maxHP = 3;
public GameObject[] hpIcons;
public AudioClip dieSound;
private void Start()
{
animator = GetComponent<Animator>();
HP = maxHP;
}
private void OnCollisionEnter2D(Collision2D collision)
{
// ★追加(敵からダメージ)
if (collision.gameObject.CompareTag("Trap") || collision.gameObject.CompareTag("Enemy")) // 条件の追加
{
HP -= 1;
HPIconManager();
animator.SetTrigger("Damage");
if (HP > 0)
{
AudioSource.PlayClipAtPoint(damageSound, transform.position);
}
else
{
AudioSource.PlayClipAtPoint(dieSound, transform.position);
Invoke("Restart", 0.15f);
}
}
}
void HPIconManager()
{
for (int i = 0; i < hpIcons.Length; i++)
{
if (i < HP)
{
hpIcons[i].SetActive(true);
}
else
{
hpIcons[i].SetActive(false);
}
}
}
void Restart()
{
SceneManager.LoadScene("Main");
}
}
敵オブジェクトの作成