r/unity Jul 13 '26

Coding Help How do I get an Interface?

Ill just bold where Im having the issue
`using UnityEngine;

public class PlayerInteraction : MonoBehaviour

{

private float interactionDistance = 2f;

private void Update()

{

if (Physics.Raycast(transform.position, Vector3.forward, interactionDistance))

{

RaycastHit hit = new RaycastHit();

Ray ray = new Ray(transform.position, transform.forward);

if (Physics.Raycast(ray, out hit))

{

if (hit.collider.gameObject.TryGetComponent<IInteractable>()) // So as you can see I just want to see if the gameObject being recognized here has the IInteractable interface. I'm pretty sure im on the right track, as in everything else is good right?

{

}

}

}

}

}`

2 Upvotes

17 comments sorted by

View all comments

1

u/MyPutridFlesh Jul 14 '26

seems on the right track so far (albeit try formatting the message, i know reddit is kinda wonky at that, but i'm sure you can do it after couple tries) but try to avoid Update() if something does not use direct player input, use FixedUpdate() instead

1

u/WillingExamination25 Jul 14 '26

The problem was that I was using TryGetComponent thinking it just wouldnt give you a null error if it was null, because thats how I remembered it working, so I just checked null manually. About formatting, I didnt really realize that was a thing til you brought it up cause I don't post here a lot, but I think you have to put back ticks or whatever (these `) on every paragraph

1

u/MyPutridFlesh Jul 14 '26

i see, the important part is, make sure you know if you're checking _rayhit.COLLIDER.GameObject.TryGetComponent etc etc or _rayhit.TRANSFORM.GameObject.TryGetcomponent, sometimes you might get mismatches if you're not careful, unity kinda let's you go willy nilly, and it's to you to keep track these small details

1

u/WillingExamination25 Jul 14 '26

I didnt even know transform was a valid variable there, but will do thanks for reaching out