Getting a specific script that implements an interface from raycasting.

Hey guys,

I have a few different objects i want to interact with but i want them to do different things and be named different things. Is there a way to just add an interface that has the method name i want to call. and from a raycast collide and call the script that has that interface on it?

I dont want to do a check for each specific object on my player i just want to have a generic check for the script containing the interface and call the interaction method.

Example:

IInteractions interactable = raycastHit.collider.gameObject.GetComponent<IInteractions>();
interactable.Interaction();

something like this?

Looks good to me … so long as you want to interact with all of them in the same way. Otherwise Interaction() will have to call some other function somewhere to handle the specific logic.

Yea i have been spending some time looking through the docs and i wasnt able to find anything that actually let me get a component that had an interface attached. apparently you can’t because the interface isnt technically the component. I got around it by calling a manager that took in a game object and from there it decided on the script to use and calls the Interaction().

Thanks for your response still!

1 Like

GetComponent works just fine with interfaces in recent unity versions. Are you seeing different?

As for different behaviors that can be handled by the different implementations of Interaction on each script.

In my use case I have a script specific to the object called workerInteraction which implements Iinteractions and has the method Interact on it.

I was attempting to on raycasthit grab the script with the IInteractions interface attached to it so I could call Interact instead of having to have abunch of if statements to see what I hit or have 1 giant script on everything i could interact with. I tried using the GetComponent() but wasnt having any luck. I tried it with type of aswell. But it’s good to know it is possible and I just messed something ekse up… Thanks!!

Hey I went through and retried it and it does indeed work! i was picking apart what i was actually interacting with in my scene and i moved all my interactable objects to there own layermask. but the code i innitially posted does work!
Thanks for letting me know it shoulc have worked so i would go back and check it out and dig deeper into why it wasnt!

Most likely your raycast was hitting a different object than you were expecting.