Get a component with a string ? [C#]

Hi everybody !

Can we get a component with his name and use his variables ?
Something like that (i tried this ^^) :

void GetAComponent (string componentName){

int  mapSizeX_xy = map.GetComponent(componentName).sizeX;

}

Thanks for answers, bye

xyHeat.

Similar Threads:

Possibly Helpful Links:

https://stackoverflow.com/questions/8723960/convert-string-to-variable-name

General consensus is to avoid doing this. It’s hacky and there’s no real reason to do it. There’s 100’s of ways to do anything with code, try thinking of an alternative. If you let me know why you would want to do this I might be able to help think of alternative approaches.

To get an arbitrary component type:

var componentType = Type.GetType(componentName);
var comp = GetComponent(componentType);

This assumes that componentName is in the same assembly and namespace or you’re specifying the fully qualified assembly name. (If these are both loose .cs scripts in your project, you’re probably fine just providing the class name.)

However, given that you’re assuming the type has a sizeX property, you should probably use subclasses and specify the base class. For example:

public class MapObject : MonoBehaviour {
    public abstract int sizeX { get; }
}

public class TileObject : MapObject {
    public override int sizeX { get { return tile.width; } }
}

public class ParticleObject : MapObject {
    public override int sizeX { get { return particleRadius; } }
}

...
int mapSizeX_xy = map.GetComponent<MapObject>().sizeX;

But even this isn’t ideal unless you can absolutely guarantee that map always has a MapObject. Otherwise something like this is better:

var mapObj = map.GetComponent<MapObject>();
if (mapObject == null) {
    Debug.LogError("No MapObject found on map. Aborting.");
    return;
}
int mapSizeX_xy = mapObj.sizeX;