팀 프로젝트 / Interact System

DEV주녁 ㅣ 2023. 11. 8. 22:16

팀프로젝트 개발 일지 #1
public abstract class Interactable : MonoBehaviour
{
    public string promptMessage;


    public void BaseInteract()
    {
        Interact();
    }

    protected virtual void Interact()
    {

    }

}

인터렉트의 근본이 되는 추상 클래스

위 클래스 상속 시 클래스의 베이스 메서드가 실행될 떄

상속을 받은 스크립트의 인터렉트 기능이 실행됨

 

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

public class PlayerInteract : MonoBehaviour
{
    [SerializeField]
    private float distance = 3f;
    [SerializeField]
    private LayerMask mask;
    private PlayerUI playerUI;

    private Camera cam;
    public Camera Cam
    {
        get
        {
            if (cam == null)
            {
                cam = Camera.main;
            }
            return cam;
        }
    }
    private void Awake()
    {
        playerUI = GetComponent<PlayerUI>();
    }

    void Update()
    {
        playerUI.UpdateText(string.Empty);
        Ray ray = new Ray(Cam.transform.position, Cam.transform.forward);
        Debug.DrawRay(ray.origin, ray.direction * distance, Color.blue);
        RaycastHit hitInfo;
        if (Physics.Raycast(ray, out hitInfo, distance, mask))
        {
            if (hitInfo.collider.GetComponent<Interactable>() != null)
            {
                Interactable interactable = hitInfo.collider.GetComponent<Interactable>();
                playerUI.UpdateText(interactable.promptMessage);

                if (Input.GetKeyDown(KeyCode.G))
                {
                    interactable.BaseInteract();
                }
            }
        }
    }
}

Raycast를 통해 닿은 물체 또는 콜라이더의 인터렉터블을 가져온다.

그후 특정 키 입력시 인터렉트 베이스 코드를 발행

 

위 설명에서 볼 수 있듯 간단하게 추상 클래스를 통해서 인터렉티브 시스템을 만들어 봤다.