I want to create a script for checking which components from an array an object has. The array is in a script called AlleFaehigkeiten and the array’s name is array. In this array there is the string “Ruestung”, name of a script. This script contains a string Name = “Rüstung”. I tried to write this “Rüstung” into the string Testname like this:

for (int i=0; i<GameObject.Find("AlleFaehigkeiten").GetComponent<AlleFaehigkeiten>().array.Length; i++) {
    			AlleFaehigkeiten Alles = GameObject.Find("AlleFaehigkeiten").GetComponent<AlleFaehigkeiten>();
    			if(gameObject.GetComponent(Alles.array*)){*

_ Testname=gameObject.GetComponent(Alles.array*).Name;_
_
}_
_
}*_
This error occured:
Type UnityEngine.Component does not contain a definition for ‘Name’ and no extension method ‘Name’ of type UnityEngine.Component could be found.
How can I correct this?

GetComponent(string type) returns an object of type Component. To do what you seem to be doing you would then need to call an explicit conversion. For instance,

 var component = gameObject.GetComponent("HingeJoint");
 var hingeJoint=component as HingeJoint;

or simply

var hingeJoint = gameObject.GetComponent("HingeJoint") as HingeJoint;

Without a conversion you can only use the component as a component. So while you can use Ruestung.Name without a conversion you are attempting to call Component.Name which doesn’t exist and why you are getting an error. However you cannot use GetComponent("string") as "string" so in you case it seems like GetComponent("string") is pretty much useless.

Consider using if/else of switch statements instead. i.e.

if(Alles.array*=="Ruestung")*

{
Testname=gameObject.GetComponent().Name;
}

or
switch(Alles.array*)*
{
case “Ruestung”:
Testname=gameObject.GetComponent().name;
break;

}

In your Alles array do you have other strings of different component types besides Ruestung? If so, in your for loop you iterate over the length of the array and your if statement is only checking to see if the other components exist on the gameObject. If they do then you are trying to assign a Name property that doesn’t exist in one of them.

Another possibility is that Name isn’t defined in Ruestung, though I’m sure you checked that already.

Also a tip on the structure of the coding you have there: when you have a loop like that where you are iterating multiple times you should declare variables that you use in each iteration before-hand to increase performance. GameObject.Find() for example is a particularly expensive method to call so doing it once rather than for each array member can really add up.