I’m trying to get an interaction system done in Unity for my project using raycast to measure the distance between player and object to interact with. Using both DrawLine and DrawRay it looks like the raycast collide with the object, but the conditions are not reached
there are 3 scripts:
Player script
public class PlayerInteraction : MonoBehaviour
{
public float interactionRange;
public GameObject interactionUI;
public TextMeshProUGUI interactionText;
private void Update()
{
InteractionRay();
}
void InteractionRay()
{
Ray ray = new Ray(transform.position, transform.forward);
RaycastHit hit;
bool hitSomething = false;
if(Physics.Raycast(ray, out hit, interactionRange))
{
Iinteractable interactable = hit.collider.GetComponent<Iinteractable>();
if (interactable != null) {
hitSomething = true;
interactionText.text = interactable.GetDescription();
if(Input.GetKeyDown(KeyCode.N))
{
interactable.Interact();
}
}
}
interactionUI.SetActive(hitSomething);
//Debug.DrawRay(ray.origin,interactionRange* ray.direction, Color.green);
Debug.DrawLine(ray.origin, hit.point, Color.red);
}
}
interface script
public interface Iinteractable {
void Interact();
string GetDescription();
}
object script:
public class Test : MonoBehaviour, Iinteractable
{
public string GetDescription()
{
return "Press";
}
public void Interact()
{
Debug.Log("Did Hit");
}
}