答案 0 :(得分:5)
取决于要在哪里获得与之匹配的名称,以及如何确定射线的原点,以下方法应该适合您。这假定光线是由运行此方法的GameObject投射的,并充当光线的来源和要匹配的名称。
public void GetFurthestObject()
{
// Replace this with whatever you want to match with
string nameToMatch = transform.name;
// Initialize the ray and raycast all. Change the origin and direction to what you need.
// This assumes that this method is being called from a transform that is the origin of the ray.
Ray ray = new Ray(transform.position, transform.forward);
RaycastHit[] hits;
hits = Physics.RaycastAll(ray, float.MaxValue);
// Initialize furthest values
float furthestDistance = float.MinValue;
GameObject furthestObject = null;
// Loop through all hits
for (int i = 0; i < hits.Length; i++)
{
// Skip objects whose name doesn't match.
if (hits[i].transform.name != nameToMatch)
continue;
// Get the distance of this hit with the transform
float currentDistance = Vector3.Distance(hits[i].transform.position, transform.position);
// If the distance is greater, store this hit as the new furthest
if (currentDistance > furthestDistance)
{
furthestDistance = currentDistance;
furthestObject = hits[i].transform.gameObject;
}
}
}