Canvas 생성 후 텍스트, 버튼 생성하고 Anchor로 위치잡아주기
UI 접근 코드는 GameManager 스크립트에서 작성
소스코드
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI; //UI에 접근하기 위해 필요
public class GameManager : MonoBehaviour
{
public int totaltemCount;
public int stage;
public Text stageCountText; //전체 Item 개수
public Text playerCountText; // 현재 플레이어가 먹은 Item 개수
void Awake()
{
stageCountText.text = "/ " + totaltemCount;
}
public void getItem(int count) { //Player 스크립트에서 함수 호출
if (count >= 10) {
stageCountText.text = " / " + totaltemCount;
}
playerCountText.text = count.ToString();
}
public void stageReset() {
SceneManager.LoadScene(stage);
}
public void goToStage0() {
SceneManager.LoadScene(0);
}
public void exit() {
Application.Quit();
}
void OnTriggerEnter(Collider other)
{
if (other.gameObject.tag == "Player") {
SceneManager.LoadScene(stage);
}
}
}
Player 소스코드 추가 (주석부분)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class PlayerBall : MonoBehaviour
{
Rigidbody rigid;
AudioSource audio;
public GameManager gm;
public float jumpPower;
bool isJumping;
public int itemCount;
void Awake()
{
rigid = GetComponent<Rigidbody>();
audio = GetComponent<AudioSource>();
jumpPower = 30;
isJumping = false;
itemCount = 0;
}
void FixedUpdate()
{
float x = Input.GetAxisRaw("Horizontal");
float z = Input.GetAxisRaw("Vertical");
Vector3 move = new Vector3(x, 0, z);
rigid.AddForce(move, ForceMode.Impulse);
}
void Update()
{
if (Input.GetButtonDown("Jump") && !isJumping)
{
isJumping = true;
rigid.AddForce(new Vector3(0, jumpPower, 0), ForceMode.Impulse);
}
}
void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.tag == "Floor")
{
isJumping = false;
}
}
void OnTriggerEnter(Collider other)
{
if (other.tag == "Item")
{
itemCount++;
audio.Play();
gm.getItem(itemCount); //플레이어가 Item을 먹을 때마다 GameManager 스크립트의 getItem 호출, itemCount를 매개변수로 줌
other.gameObject.SetActive(false);
}
else if(other.tag == "Finish") //스테이지 이동 로직
{
if (gm.totaltemCount == itemCount) {
//Game Clear!
if (gm.stage == 2)
{
Debug.Log("You won! Stage Reset");
SceneManager.LoadScene(0);
}
else
{
SceneManager.LoadScene(gm.stage + 1);
}
}
else {
SceneManager.LoadScene(gm.stage);
}
}
}
}
결과
'유니티 3D기본(Roll A Ball)' 카테고리의 다른 글
23 . 게임 빌드 (0) | 2021.10.27 |
---|---|
22. 플레이어가 맵에서 낙하 시 리스폰 (0) | 2021.10.27 |
20. Scene 추가 (0) | 2021.10.27 |
19. 스테이지 이동 (0) | 2021.10.26 |
18. 카메라 이동으로 플레이어 따라가기 (0) | 2021.10.26 |