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?
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:
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.