본문 바로가기
유니티강좌

아이템 줍기(획득, 먹기). 아이템에 접근시 특정키 누르라는 메시지 띄우기. How to text to appear when Pick Up Item | 유니티 게임 개발 튜토리얼(Unity & C# Script)

by Ncube 2021. 1. 24.

 

 

로봇 캐릭터가 좌우로 이동하여 바닥에 놓여진 무기 아이템에 접근시(Collision) 화면에 "특정키를 누르면 아이템 획득"한다는 메시지가 뜨고 그 특정키를 누르면 아이템이 사라지게 됩니다.

 

 

[Robot.cs]

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Robot : MonoBehaviour
{
    [SerializeField] float speed;
    float moveX;
    Rigidbody2D rb;

    void Start()
    {
        rb = GetComponent<Rigidbody2D>();
    }

    void Update()
    {
        moveX = Input.GetAxis("Horizontal") * speed;
        rb.velocity = new Vector2(moveX, rb.velocity.y);
    }
}

 

 

[Item.cs]

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Item : MonoBehaviour
{
    [SerializeField] Text pickUpText;
    bool isPickUp;

    void Start()
    {
        pickUpText.gameObject.SetActive(false);
    }

    void Update()
    {
        if (isPickUp && Input.GetKeyDown(KeyCode.Space))
            PickUp();
    }

    void OnTriggerEnter2D(Collider2D col)
    {
        if (col.gameObject.tag.Equals("Player"))
        {
            pickUpText.gameObject.SetActive(true);
            isPickUp = true;
        }
    }

    void OnTriggerExit2D(Collider2D col)
    {
        if (col.gameObject.tag.Equals("Player"))
        {
            pickUpText.gameObject.SetActive(false);
            isPickUp = false;
        }
    }

    void PickUp()
    {
        Destroy(gameObject);
    }
}

 

댓글