Skip to content

Instantly share code, notes, and snippets.

@IshidaGames
Created June 27, 2019 07:22
Show Gist options
  • Save IshidaGames/c0abcf9ff65bca62a076a6375f7bcc82 to your computer and use it in GitHub Desktop.
Save IshidaGames/c0abcf9ff65bca62a076a6375f7bcc82 to your computer and use it in GitHub Desktop.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
//UI使うときは忘れずに。
using UnityEngine.UI;
public class PlayerHPBar : MonoBehaviour
{
//最大HPと現在のHP。
int maxHp = 155;
int currentHp;
//Sliderを入れる
public Slider slider;
void Start()
{
//Sliderを満タンにする。
slider.value = 1;
//現在のHPを最大HPと同じに。
currentHp = maxHp;
Debug.Log("Start currentHp : " + currentHp);
}
//ColliderオブジェクトのIsTriggerにチェック入れること。
private void OnTriggerEnter(Collider collider)
{
//Enemyタグのオブジェクトに触れると発動
if (collider.gameObject.tag == "Enemy")
{
//ダメージは1~100の中でランダムに決める。
int damage = Random.Range(1, 100);
Debug.Log("damage : " + damage);
//現在のHPからダメージを引く
currentHp = currentHp - damage;
Debug.Log("After currentHp : " + currentHp);
//最大HPにおける現在のHPをSliderに反映。
//int同士の割り算は小数点以下は0になるので、
//(float)をつけてfloatの変数として振舞わせる。
slider.value = (float)currentHp / (float)maxHp; ;
Debug.Log("slider.value : " + slider.value);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment