Unity-Prefab, 예제-랜덤한 위치에 화살생성, hp게이지 만들기
2023. 8. 2.

 

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

 

Unity - Manual: Prefabs

Prefabs Unity’s Prefab system allows you to create, configure, and store a GameObjectThe fundamental object in Unity scenes, which can represent characters, props, scenery, cameras, waypoints, and more. A GameObject’s functionality is defined by the Co

docs.unity3d.com

 

-프리팹 시스템을 사용하면 게임 오트젝트를 저장할 수 있다.

-> 게임오브젝트가 파일화된것.

-파일은 모두 프로젝트 창에있다.

 

프리팹 복제를 해서 인스턴스를 만든것.

-Hierachy에 있는것이 아니라 프로젝트 폴더에 파일화 되어있는것이 프리팹이다.

-프로젝트에 생성된 프리팹을 복제하여 hierachy에 오브젝트를 추가(프리팹의 인스턴스 생성)하면 그 오브젝트는 프리팹과 링크되어있다.

만약 프리팹을 삭제하면 원본이 없어져 unlink된다.

 

Unpack

-링크를 끊을 수 있다.

 

-하늘에서 화살이 떨어지게함 => 같은 동작을 하는 오브젝트들이 필요함: 프리팹 생성

 

 

-ArrowGenerator.cs 작성

1. 화살을 만든다. => 동적으로 게임 오브젝트 생성

2.랜덤한 x좌표에

3.일정한 시간 간격마다

Instantiate<GameObject>라고 써야하지만 <>를 생략할 수도 있다.

 

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);//랜덤한 위치를 정해줌

    }
}

 ArrowGenerator넣어줌
ArrowController 수정

 

 

hp게이지 만들기

UI-Image로 hpGage오브젝트 생성 사진에는 hpGauge인데 나는 hpGage라고 함

 

버튼 만들어서 키보드 말고 버튼누르면 움직이는 걸로 코드수정

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;
       
    }
}

 

 

CatController.cs에 버튼 내용 수정하고 버튼 오브젝트의 onclick추가

 

 

myoskin