Unity-Prefab, 예제-랜덤한 위치에 화살생성, hp게이지 만들기
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CatController : MonoBehaviour
{
public float radius = 1;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
//키 입력받기
if(Input.GetKeyDown(KeyCode.LeftArrow))
{//왼쪽 화살표를 눌렀다면 x축으로 -3유닛만큼이동
MoveLeft();
}
else if (Input.GetKeyDown(KeyCode.RightArrow))
{//오른쪽 화살표를 눌렀다면 x축으로 3유닛만큼이동
MoveRight();
}
}
private void OnDrawGizmos()
{
Gizmos.color = Color.red;
Gizmos.DrawWireSphere(this.transform.position, this.radius);
}
public void MoveLeft()
{
this.transform.Translate(-3, 0, 0);
}
public void MoveRight()
{
this.transform.Translate(3, 0, 0);
}
}
https://docs.unity3d.com/Manual/Prefabs.html
-프리팹 시스템을 사용하면 게임 오트젝트를 저장할 수 있다.
-> 게임오브젝트가 파일화된것.
-파일은 모두 프로젝트 창에있다.
-Hierachy에 있는것이 아니라 프로젝트 폴더에 파일화 되어있는것이 프리팹이다.
-프로젝트에 생성된 프리팹을 복제하여 hierachy에 오브젝트를 추가(프리팹의 인스턴스 생성)하면 그 오브젝트는 프리팹과 링크되어있다.
만약 프리팹을 삭제하면 원본이 없어져 unlink된다.
Unpack
-링크를 끊을 수 있다.
-하늘에서 화살이 떨어지게함 => 같은 동작을 하는 오브젝트들이 필요함: 프리팹 생성
-ArrowGenerator.cs 작성
1. 화살을 만든다. => 동적으로 게임 오브젝트 생성
2.랜덤한 x좌표에
3.일정한 시간 간격마다
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ArrowGenerator : MonoBehaviour
{
public GameObject arrowPrefab;//프리팹 원본파일
private float elapsedTime;//경과시간
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
//매프레임마다 Time.deltaTime을 경과시간에 더해줌
this.elapsedTime += Time.deltaTime;
if(this.elapsedTime > 1f)
{ //경과시간이 1초를 넘어갔다면
//화살생성
this.CreateArrow();
this.elapsedTime = 0; //0초부터 1초까지를 셀수있도록 초기화
}
}
private void CreateArrow()
{
GameObject arrowGo = Object.Instantiate(this.arrowPrefab);//원본프리팹을 복사본 arroGo에 넣어줌
//arrGo 는 프리팹으 복제본. 원본파일로부터 생성된 프리팹 인스턴스
var random = Random.Range(-7, 8);
arrowGo.transform.position = new Vector3(random, 6f, 0);//랜덤한 위치를 정해줌
}
}
hp게이지 만들기
버튼 만들어서 키보드 말고 버튼누르면 움직이는 걸로 코드수정
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class GameDirector : MonoBehaviour
{
private GameObject catGo;
private GameObject hpGageGo;
// Start is called before the first frame update
void Start()
{
this.catGo = GameObject.Find("cat");
this.hpGageGo = GameObject.Find("hpGage");
Debug.LogFormat("{0},{1}", catGo, hpGageGo);
Image hpGage = this.hpGageGo.GetComponent<Image>();
hpGage.fillAmount = 0.5f;
}
public void DecreaseHp()
{
Image hpGage = this.hpGageGo.GetComponent<Image>();
hpGage.fillAmount -= 0.1f;
}
}
'유니티 기초' 카테고리의 다른 글
애니메이션 전환 연습 (0) | 2023.08.03 |
---|---|
Unity-Physics,Rigidbody, 스프라이트 애니메이션, ClimbCloud 예제 (0) | 2023.08.02 |
Unity-Player Setting에서 Deafult Orientaiton (0) | 2023.08.02 |
Unity- CatEscape 예제, time (0) | 2023.08.01 |
Unity-자동차 스와이프 예제2-UI, 사운드추가 (0) | 2023.08.01 |