Hi,
I’ve create a script for getting object nearest of the player because RayCastHit when you are too near in the range that stop detecting it.
I would like to only get the object in front of the player inside the range not around the player
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
public class ObjectDetector : MonoBehaviour
{
[SerializeField]
private string _message;
public string MessageGet { get => _message; set => _message = value; }
//detection range
float range = 5;
private GameObject target;
List<GameObject> getObject = new List<GameObject>();
// Start is called before the first frame update
void Start()
{
GetAllObject();
}
// Update is called once per frame
void Update()
{
GetClosestObject(getObject,this.gameObject);
Debug.Log(Vector3.Distance(transform.position, target.transform.position));
if (Vector3.Distance(transform.position + transform.forward, target.transform.position) <= range)
{
if (target.tag == "GetObject")
{
var objbehavior = target.transform.GetComponent<ObjectBehavior>();
MessageGet = "Press (E) to get " + target.transform.name + " x" + objbehavior.Nombre;
}
else { MessageGet = ""; }
}
else { MessageGet = ""; }
}
public void GetClosestObject(List<GameObject> Object, GameObject fromThis)
{
GameObject bestTarget = null;
float closestDistanceSqr = Mathf.Infinity;
Vector3 currentPosition = fromThis.transform.position;
foreach (GameObject potentialTarget in Object)
{
Vector3 directionToTarget = potentialTarget.transform.position - currentPosition;
float dSqrToTarget = directionToTarget.sqrMagnitude;
if (dSqrToTarget < closestDistanceSqr)
{
closestDistanceSqr = dSqrToTarget;
bestTarget = potentialTarget;
}
}
target = bestTarget;
}
public void GetAllObject()
{
GameObject[] items= GameObject.FindGameObjectsWithTag("GetObject");
foreach (var item in items)
{
getObject.Add(item);
}
}
}