I’m currently working on an interaction system for my project but I seem to not be getting the results I’ve expected. I assumed it might’ve been my camera system at first (I assumed the ray was not shooting out from the center of my camera) but it doesn’t seem so as far as I can tell . What I’m trying to accomplish is that when I look at an object, it tells me if it’s interactable, if it was interacted with, and when you look away from said object also lets me know, but right now it doesn’t seem to be working like that. It’s not displaying the messages in console as expected, which leaves me to believe there’s some issue with either the Raycast or my detection code. There is also a pretty major lag spike when pressing the interact key for the first time the game is loaded into, which leads me to believe the code is running to some degree, but definitely not properly because it freezes for whole second.
Here’s the functions that run my interaction code:
private void InteractionCheck()
{
if(Physics.Raycast(playerCam.ViewportPointToRay(interactRayPoint), out RaycastHit hit, interactDistance))
{
if (hit.collider.gameObject.layer == 9 && (currentInteractable == null || hit.collider.gameObject.GetInstanceID() != currentInteractable.GetInstanceID()))
{
hit.collider.TryGetComponent(out currentInteractable);
if (currentInteractable)
currentInteractable.OnFocus();
}
}
else if (currentInteractable)
{
currentInteractable.OnLoseFocus();
currentInteractable = null;
}
}
private void InteractionInput()
{
if (Input.GetKeyDown(interactKey) && currentInteractable != null && Physics.Raycast(playerCam.ViewportPointToRay(interactRayPoint), out RaycastHit hit, interactDistance, interactLayer))
{
currentInteractable.OnInteract();
}
}
Here’s the class that is referenced in the first excerpt:
public abstract class Interactable : MonoBehaviour
{
public virtual void Awake()
{
gameObject.layer = 3;
}
public abstract void OnInteract();
public abstract void OnFocus();
public abstract void OnLoseFocus();
}
And here’s the messages I’m expecting to receive in console, but am not:
public class InteractableObject : Interactable
{
public override void OnFocus()
{
print("LOOKING AT " + gameObject.name);
}
public override void OnInteract()
{
print("INTERACTED WITH " + gameObject.name);
}
public override void OnLoseFocus()
{
print("STOPPED LOOKING AT " + gameObject.name);
}
}
Additional Information:
Box on interactable layer
Controller script set up to fire raycasts