Detect which gameobject hit by SphereCast

Hello,

I want to be able to SphereCast and depending on which object the SphereCast hits then a different function will run specific towards that gameobject.

At the moment I have a script that has this:

if (Physics.SphereCast(origin, radius, direction, hit){
GazeTarget target =gazeRayHit.collider.gameObject.GetComponent<GazeTarget>();
if (target != null)
target.OnHit();
}

So when the Cast hits the gameObject that has the GazeTarget script then it runs the OnHit command from the GazeTarget script which works fine. I want to be able to run a different script/function depending on which gameobject I am looking at though and this currently has me stumped. For example I want to look at a car and display information about that car then if i look at a truck then information will pop up about the truck… etc.

Any help would be greatly appreciated!

Hi and welcome,

Why not use C# and generally OOP principles and have your different things as classes that derive from a base class? In your example case you could have a base Vehicle class, from which you derive classes like Car, Truck and so on.

You could then have some abstact or virtual methods and variables in that base class which you could use to your benefit. You could for example require your derived classes to provide information about the vehicle type.

Make GazeTarget an interface and then make your various information scripts inherit from the interface.

Thank you for the answers Olmi and Madgvox. I realized I was overthinking it and I did basically what both of you mentioned. I did just use the same script and had it inherit other information scripts and it worked just fine.

Thanks for the answers!