So I’m trying to have a raycast fire at the nearest target and return the object’s that was hit name. I added Debug.Draw to see if it was the raycast and as far as I see the raycast doesn’t do anything, not sure what I did wrong; please help.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GrappleHook : MonoBehaviour
{
public RaycastHit HitInfo;
private GameObject GetClosestTarget(string targetTag)
{
GameObject closestTarget = null;
float closestDistance = 3.0F;
foreach (GameObject target in GameObject.FindGameObjectsWithTag(targetTag))
{
float dist = Vector3.Distance(transform.position, target.transform.position);
if (dist < closestDistance)
{
closestTarget = target;
closestDistance = dist;
}
}
return closestTarget;
}
private void Update()
{
GameObject ClosestTarget = GetClosestTarget("Enemy");
transform.LookAt(ClosestTarget.transform);
if(Physics.Raycast(transform.position, transform.forward, out HitInfo))
{
print(HitInfo.collider.gameObject.name);
Debug.DrawLine(Vector2.zero, HitInfo.point); //Doesn't Draw Anything
}
}
}
If you want to see where the raycast is visually, debug outside the raycast
Debug.DrawLine(transform.position, transform.forward, Color.red);
if(Physics.Raycast(transform.position, transform.forward, out HitInfo))
{
print(HitInfo.collider.gameObject.name);
}
This will draw a red line from your character to 1meter forward - which is the exact length and direction of your raycast.
I think it is drawing but just too short to see because you added no distance. Maybe.
Try the code below:
private void Update()
{
GameObject ClosestTarget = GetClosestTarget("Enemy");
transform.LookAt(ClosestTarget.transform);
Debug.DrawRay(transform.position, transform.TransformDirection(Vector3.forward) * 2, Color.white);
if(Physics.Raycast(transform.position, transform.forward, out HitInfo))
{
Debug.DrawRay(transform.position, transform.TransformDirection(Vector3.forward) * 1000, Color.Red);
}
}
}
Oh it’s only in the scene view, size isn’t a problem; it went as far as I could see, but now I know the raycast is what is wrong with the code, it wont follow the closest target like I want. Thank You For The Help.