Player
변수 // 게임저장소에 인식
프로퍼티
대리자 선언
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HeroController : MonoBehaviour
{
private HeroDataManager heroDataManager; //게임저장소
//private int maxhp;
//public int hp;
public int Hp { get; set; } //속성 ; 외부 접근 가능 = this.hp
public int MaxHp { get; set; } //속성 ; 외부 접근 가능 = this.hp
// Start is called before the first frame update
public System.Action onHit; //대리자
void Start()
{
this.MaxHp = 10;
this.Hp = this.MaxHp;
}
// Update is called once per frame
void Update()
{
if (Input.GetMouseButtonDown(0))
{
this.Hp -=1;
if( this.Hp <= 0 ){
this.Hp = 0;
}
this.onHit(); //대리자 호출
}
}
}
UI
텍스트
버튼
람다식//
게임씬 전환
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class GameSceneMain : MonoBehaviour
{
[SerializeField] private Text textHp;
[SerializeField] private Button btnLoadScene;
[SerializeField] private GameObject heroprefab;
[SerializeField] private HeroDataManager heroDataManager;
// Start is called before the first frame update
void Start()
{
this.btnLoadScene.onClick.AddListener(() =>
{
SceneManager.LoadScene("Village");
});
this.CreateHero();
}
private void CreateHero()
{
GameObject heroGo = Instantiate(this.heroprefab);
HeroController heroController= heroGo.GetComponent<HeroController>();
heroController.onHit = () =>
{
Debug.LogFormat("{0}{1}", heroController.Hp,heroController.MaxHp);
this.heroDataManager.UpdateHeroHpAndMaxHp(heroController.Hp, heroController.MaxHp);
this.textHp.text = string.Format("{0}/{1}",heroController.Hp,heroController.MaxHp);
}; //람다, 매서드-> 대리자 변수
}
}
Data
데이터 저장 -> 씬 전환후 호출 가능
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HeroDataManager : MonoBehaviour
{
public int heroHp = 0;
public int heroMaxHp = 0;
private void Awake()
{
DontDestroyOnLoad(this.gameObject);
}
public void UpdateHeroHpAndMaxHp(int heroHp, int heroMaxHp)
{
this.heroHp = heroHp;
this.heroMaxHp = heroMaxHp;
}
public int GetHeroHp()
{
return this.heroHp;
}
public int GetHeroMaxHp()
{
return this.heroMaxHp;
}
}
씬전환 // 텍스트 데이터 불러오기
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class VillageSecen : MonoBehaviour
{
private HeroDataManager heroDataManager;
private int hp;
private int maxHp;
public Text textHp;
void Start()
{
this.heroDataManager = GameObject.FindFirstObjectByType<HeroDataManager>();
this.hp = this.heroDataManager.heroHp;
this.maxHp = this.heroDataManager.heroMaxHp;
}
// Update is called once per frame
void Update()
{
this.textHp.text = string.Format("{0}/{1}",this.hp,this.maxHp);
}
}
'게임개발 > 게임 클라이언트 프로그래밍' 카테고리의 다른 글
AppleCatch(3) 오류 해결 (1) | 2024.02.07 |
---|---|
AppleCatch(2) 게임 결과 화면 오류 수정 전 (1) | 2024.02.07 |
AppleCatch (1) (1) | 2024.02.05 |
ShootingSpace (5) 배경 스크롤링 (0) | 2024.02.04 |
ShootingSpace (4) 아이템 먹고 총알 업그레이드 (1) | 2024.02.04 |