본문 바로가기
C#

[C#][Unity] 상자 열고 닫기

by teamnova 2022. 8. 12.

안녕하세요. 

오늘은 게임에서 상자 열고 닫는 것을 진행해보겠습니다.

 

유니티 버전 - 2021.3.4f1

 

먼저 글 하단에 있는 링크에서 상자를 다운받고 sprite slice로 2등분합니다.

 

먼저 계층구조에서 emptyObject (빈 오브젝트생성) 을 하겠습니다.

오브젝트에 위에서 자른 상자이미지 두개를 넣어줍니다.

해당 오브젝트에 Box collider 2D를 추가해주세요

 

그리고 asset에 새 "interactable"이라는 스크립트를 생성합니다

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

public class Interactable : MonoBehaviour
{
    public virtual void Interact(Character character){

    }
}

 

그다음 위에서 생성한 오브젝트 안에 새 스크립트를 생성하겠습니다. 

//LootContainerInteract.cs

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

public class LootContainerInteract : Interactable
{
    [SerializeField] GameObject closedChest;
    [SerializeField] GameObject openedChest;
    [SerializeField] bool opened;

    public override void Interact(Character character)
    {
       if(opened == false){
            opened = true;
            closedChest.SetActive(false);
            openedChest.SetActive(true);
       } 
    }
}

그 다음 오브젝트 안에 넣은 상자 이미지를 closedChest, openedChest 에 각각 넣어줍니다.

 

 

그리고 각자가 사용하는 캐릭터 안에 새 스크립트 컴포넌트를 생성합니다.

 

//CharacterInteractController.cs

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

public class CharacterInteractController : MonoBehaviour
{
    CharacterController2D characterController;
    Rigidbody2D rigid;
    [SerializeField] float offsetDistance = 1f;
    [SerializeField] float sizeOfInteractableArea = 1.2f;

    Character character;

    private void Awake()
    {
        characterController = GetComponent<CharacterController2D>();
        rigid = GetComponent<Rigidbody2D>();
        character = GetComponent<Character>();
    }

    private void Update(){
        if(Input.GetMouseButtonDown(1)){
            Interact();
        }
    }

    private void Interact(){
        Vector2 position = rigid.position + characterController.lastMotionVector * offsetDistance; //캐릭터 위치, 캐릭터 방향, offset
        Collider2D[] colliders = Physics2D.OverlapCircleAll(position, sizeOfInteractableArea);

        foreach(Collider2D c in colliders){
            Interactable hit = c.GetComponent<Interactable>();
            if(hit != null){
                hit.Interact(character);
                break;
            }
        }
    }
}

 

이제 실행해보겠습니다.

 

 

 

[추가]

캐릭터에 사용하는 스크립트 입니다. 

 

//Character.cs

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

public class Character : MonoBehaviour
{
    void Start()
    {}

    void Update()
    {}
}

 

 

[상자이미지 출처]

https://opengameart.org/content/modified-32x32-treasure-chest