Help! Access various components through script

Hello, Unity commUnity. I have been struggling with this problem for quite some time now.
I have a game, (using C#) where enemy units will pickup random weapons from the map and fight me. I’m having trouble with accessing the components that control different guns. For example, each type of gun has one script to operate it but the class is of a different name.

  • Standard guns use a class called “gun_main”
  • Special guns like an energy beam emitter use a class called “focusCannon_main”
  • and grenade launchers use a script class “launcher_main”

Now I know that if they all use a script of the same class type, the variables can be changed from the inspector, but if I want different weapons to have different functions such as a timed release to detonate a grenade in the air, or cause some weapons to overheat but not others, how can I tell the ai what component to retrieve in order to execute the functions?

  • ai.GetComponent<gun_main>() would not retrieve “launcher_main” and therefore I cannot get the ai to shoot anything other than something using gun_main

a switch statement could solve this for sure, but with more and more classes, that will get very lengthy.
This is a big deal because I also have the AI use different class scripts for different gametypes like Capture the Flag and Infection simply for organization and CPU performance, so I would also need to know what script they are using and a way to get that component with GetComponent.()
Is there a way to do this?
Simply put, I am looking for how to accomplish this and implement the result into GetComponent
The script will find a component matching one of the _mains above.

  • ai.GetComponent(the_matching_component).shoot();

Thank you in advance, I really need your help.

The simplest (and probably best) solution is to define an interface for all your guns (or shootables or weapons or whatever you want to call them). This interface will define the public methods which all such guns implement: maybe CanFire to see if it’s ready to go (has ammo etc.), and then Fire to actually do whatever it does.

Then you can call GetComponent (or GetComponents if there might be more than one) to get any component that implements that interface, and use the interface method to tell it to do its thing.

As it happens, I just sketched out (with some sample code) just this sort of solution in another thread. Perhaps it will be useful to you as well.

Oh wow! I never thought about using an interface. I think this is exactly what I was looking for. So if I call GetComponent(), then that could get a component by any name as long as I include the interface in the code like this?
public class assault : MonoBehavior, IGun
{
}

Yes, that’s exactly right.

Thank you. I appreciate your help. Nice picture in the post by the way, your game looks good.