- Home /
Component referenciated with a String?
Hello, I'm trying to make a script that activates a component in another object colliding, but I do not want the component is fixed, I will reference the component with a String to reuse this code to reference any component. I need to know if this can be done.
Here is the code that I want to do that I get error and below is the code that works but has the fixed component.
//I have a script called Weapon
var component:String; //(the string component="Weapon")
function OnTriggerEnter (collider:Collider) {
var compClass:System.Object;
compClass=collider.gameObject.GetComponent(component);
print(compClass.GetType()); // This return Weapon
compClass.enabled=true; // this give me an error
}
//----------------------------------------------------------
//code that works but has the fixed component.
function OnCollisionEnter (collision:Collision) {
var compClass:Weapon;
compClass=collision.gameObject.GetComponent(component);
print(compClass.GetType());// This return Weapon
compClass.enabled=true;
}
Thanks
$$anonymous$$ake compClass a string and set it to weapon and it will use the string version of GetComponent which will require a cast to be the correct type or System.Type should allow you to pass an actual type, which will return an object of that type should it exist. In both cases you will need some base class or interface if you want to work with the object - perhaps $$anonymous$$onoBehaviour is enough (for the enabled property?)
Thank you very much $$anonymous$$ike, monobehaviour is the solution for this script. Excuse me I'm no expert, could you give me an example of how it would be used to compClass as string and use the string version getComponent?, And as would be used System.Type. I found the following code does not work.
var weaponScript:System.Type= System.Reflection.Assembly.GetExecutingAssembly().GetType(component);
print(weaponScript.GetSituationState());//give me an error
You should be able to use a string for your component but it is a little slower. I remember getting some warnings when using them like "You are casting down" or something like this.
At least, the string use is explained in the docs as well.
What if you just let the compiler do the conversion and choose the appropriate type:
var compClass=collider.gameObject.GetComponent(component);