점수 UI
Text UI 배치
빈 오브젝트 Director + 스크립트 Director
감독 스크립트
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Director : MonoBehaviour
{
Text scoreUi;
public int score;
void Start()
{
this.scoreUi = GameObject.Find("Score").GetComponent<Text>();
}
void Update()
{
this.scoreUi.text = string.Format("Score {0}", this.score);
}
}
적 스크립트
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyA : MonoBehaviour
{
public float hp;
public GameObject playerBullet;
GameObject playerMainBullet;
GameObject playerSubBullet;
Animator animator;
GameObject diretor;
bool isHit = false;
void Start()
{
this.playerSubBullet = this.playerBullet.transform.GetChild(0).gameObject;
this.playerMainBullet = this.playerBullet.transform.GetChild(1).gameObject;
this.animator = GetComponent<Animator>();
this.diretor = GameObject.Find("Director");
}
void Update()
{
this.transform.Translate(Vector2.down * 2 * Time.deltaTime);
this.animator.SetBool("isHit", isHit);
this.isHit = false;
//처치당하면
if (this.hp <= 0)
{
this.diretor.GetComponent<Director>().score += 10;
Destroy(this.gameObject);
}
//화면밖으로 나가면
if (this.gameObject.transform.position.y <= -6.0f)
{
Destroy(this.gameObject);
}
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.CompareTag("Bullet"))
{
if (collision.gameObject.name == "SubBullet")
{
this.hp -= this.playerSubBullet.GetComponent<BulletTrigger>().damage;
this.isHit = true;
}
if (collision.gameObject.name == "MainBullet")
{
this.hp -= this.playerMainBullet.GetComponent<BulletTrigger>().damage;
this.isHit = true;
}
}
}
}
| GameObject diretor; this.diretor = GameObject.Find("Director"); this.diretor.GetComponent<Director>().score += 10; |
플레이어 사망
Enemy 태그의 콜라이더와 충돌시 생명 감소

private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.CompareTag("Enemy"))
{
if (this.life > 0)
{
Debug.LogFormat("Life : {0} / Hit", this.life);
this.life -= 1;
}
else
{
Debug.Log("GameOver");
}
}
}
UI와 연결하기

private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.CompareTag("Enemy"))
{
if (this.life > 0)
{
GameObject life = GameObject.Find("Life");
life.transform.GetChild(this.life - 1).gameObject.SetActive(false);
this.life -= 1;
}
else
{
Debug.Log("GameOver");
//사망하면 비활성화(임시)
this.gameObject.SetActive(false);
}
}
}
| GameObject life = GameObject.Find("Life"); life.transform.GetChild(this.life - 1).gameObject.SetActive(false); Image UI의 인덱스로 자식에 접근하여 비활성화 (life변수를 인덱스로 사용) |
'Unity > 게임 엔진 응용 프로그래밍' 카테고리의 다른 글
| Vertical 2D Shooting 08 : 코인 이이템 드롭 (0) | 2021.10.15 |
|---|---|
| 코루틴(Coroutine) (0) | 2021.10.14 |
| Vertical 2D Shooting 06 : 적기 자동생성, 피격 애니메이션 (0) | 2021.10.14 |
| Vertical 2D Shooting 05 : 적기 파괴 (0) | 2021.10.13 |
| Vertical 2D Shooting 04 : 레이어된 배경 스크롤링 (0) | 2021.10.13 |