Polymorphism and GetComponent

Hi

I don’t know if what I’am trying to do is possible : (In C#)

I have a base “Class A” who have a for example a member “Name”.

And I have some derived Class, B, C, D, etc who derive from A.

These script are used on some gameObject in the scene and I want to modify “name” in another script.

So I try to do :

A myAInstance = GetComponent(typeof(A))
myAInstance.name = “bob”;

but unity don’t find the script.
I have to call GetComponent with the good type, apparently I can’t use the base type to do this.

Any Idea ?

Thanks

Jérôme Foucher

this will work, i think

Component cs = gameObject.GetComponents(typeof(Component)) as Component[];

MyClass mc;

foreach(Component c in cs){
	if(c is MyClass){
		 mc = c as MyClass ;
		break;
	}
}

I have an interface IInfo, which 2 classes implement. I can freely call GetComponent(typeof(IInfo)) and get either of the 2 classes.

So I believe it should work.

A is MonoBehaviour or a MonoBehaviour derived class, right? If so, you shouldn’t have a problem and more information (like code) would be needed to determine the problem.

Maybe you just subclassed from MonoBehaviour (default code generated by unity) and forgot to change to base type.

You replied to a 5 years old thread…

@Dantus : If his answer helps some else, so what if he answered a 5 year old post?

It is a very vague statement and meanwhile GetComponent changed and e.g. supports interfaces. Not sure how it could be useful.