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

public class OverlapPlayer : MonoBehaviour
{
    [SerializeField] private float radius = 1f;
    [SerializeField] private Transform gunAttachPoint;  // 장착 위치
    private Collider[] colliders = new Collider[3];

    private void Start()
    {
        int layerMask = 1 << LayerMask.NameToLayer("Gun");
        int cnt = Physics.OverlapSphereNonAlloc(this.transform.position, this.radius, colliders, layerMask);

        Collider nearestGun = null;
        float minDistance = float.MaxValue;

        foreach (Collider col in colliders)
        {
            if (col != null)  // 중요: null 체크
            {
                float distance = Vector3.Distance(this.transform.position, col.transform.position);
                if (distance < minDistance)
                {
                    nearestGun = col;
                    minDistance = distance;
                }
            }
        }

        if (nearestGun != null)
        {
            nearestGun.transform.SetParent(gunAttachPoint.transform); // 장착 (자식 객체로 설정)
            nearestGun.transform.localPosition = Vector3.zero;  // 장착 위치로 이동 
            nearestGun.transform.localRotation = Quaternion.identity;  // 장착 위치의 회전을 적용 
        }
    }

    private void OnDrawGizmos()
    {
        Gizmos.DrawWireSphere(this.transform.position, radius);
    }
}

+ Recent posts