is it possible to get a non-spesific script from an object with GetComponent

Is it possible to call a method in a non-specific script with getComponent? I my situation I know that all of the 5 possible scripts have a method called Upgrade (); but the name of the scripts differ. is it possible to call the method without having the specific script name?

C# is preferred :smiley:

Short answer, no. You need the class name to use GetComponent. How else does it know what script you mean or the class of the returned reference?

HOWEVER you can use SendMessage to invoke a method on every script on the gameobject that has that method defined.

See Unity - Scripting API: GameObject.SendMessage

Your scripts could implement an interface like this:

public interface IUpgradeable
{
    void Upgrade();
}

Since the generic version of GetComponent only accepts types derived from Component you have to use the non generic version:

IUpgradeable script = (IUpgradeable)GetComponent(typeof(IUpgradeable));
if (script != null)
    script.Upgrade();

Your scripts all need to implement the interface in order to be “detected”:

public class SomeScript : MonoBehaviour, IUpgradeable
{
    // ...
    public void Upgrade()
    {
        
    }
}

If you want to use that pattern more often you can implement extension methods like those:

public static class InterfaceComponents
{
    public static T GetInterface<T>(this GameObject aObj) where T : class
    {
        return aObj.GetComponent(typeof(T)) as T;
    }
    public static T GetInterface<T>(this Component aObj) where T : class
    {
        return aObj.GetComponent(typeof(T)) as T;
    }
}

So you can easily use them in replace of GetComponent:

gameObject.GetInterface<IUpgradeable>();

This is possible, using polymorphism. If all of your scripts implement from a common base class, or all of your scripts implement a common interface.

MyInterface myInterface = (MyInterface) GetComponent(typeof(MyInterface));
myInterface.DoMethod();

Note that GetComponent will only return the first component of the type found. You can use GetComponents if you need to find all components of the type.