Unity accessing members of an object

How do I access the members of an object, not a gameobject, but an object created from a different class?

I would like to pass in an object and then call a function from it or access it’s public variables.

I can find the type of the object, check if the type matches a set type and then cast the object to that type to then call functions from it but I was hoping to find a more generic way of doing this.

I was just hoping to have a catch all sort of object, cast it to the right type (it’s own type) and then call members from the object but I haven’t figured out any sort of smooth way to do this. I’m trying to avoid using a switch statement for all the different types the object can be, and just cast the object to what it is or pretty much what getType says the type should be.

Pretty much I want to avoid this:

pigClass w = EnemyObj as pigClass;

and want to do something like this:

var v = EnemyObj.GetType();


x = EnemyObj as v;

This is what I have script wise…

public object EnemyObj;
public allEnemiesC getEclass;

....

    getEclass = this.GetComponent("allEnemiesC") as allEnemiesC;
        
        EnemyObj = getEclass.SelectedObj(type);
        
        if (EnemyObj.GetType() == typeof(pigClass)) //--- works
        {
        	Debug.Log("Works");
        	pigClass w = EnemyObj as pigClass; //must cast to access members
        	Debug.Log (w.eName);
        
        }
        else
        {
        	Debug.Log("not working!");
        }

And I’ve sorta looked at generics, and invoke methods and was kind of hoping there was an easier way to do this.

Also why do I need to recast this again if
(EnemyObj.GetType() == typeof(pigClass)) is true?

It feels like pigClass w = EnemyObj as pigClass; is redundant,

but EnemyObj is just a Object that has the pigClass object passed to it…

It returns an error if I skip casting of course, object does not have a definition blah blah…

So, my question is how can I cast to what the object is from getType?

var v = EnemyObj.GetType();


x = EnemyObj as v;

Use an inheritance or interface:

IMyObjectType{
   void Method();
}

public class MyObject:MonoBehaviour,IMyObjectType{
   public void MyMethod(){
      print("MyObject");
   }
}
public class MyOtherObject:MonoBehaviour,IMyObjectType{
   public void MyMethod(){
      print("MyOtherObject");
  }
}

public class Manager:MonoBehaviour{
   void Start(){
      IMyObjectType [] objs = (IMyObjectType[])FindObjectsOfType(typeof(IMyObjectType));
      foreach(IMyObjectType t in objs){
         t.Mymethod();
      }
   }
}