C# Enable component on another GameObject using name of component
I spent many hours on finding an answer but no success. Thing is simple. After timeOut, a component on another gameobject will become active. It looks like this:
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class TimedObjectEnableComponent : MonoBehaviour {
public float timeOut = 1;
public GameObject go;
public string NameOfComp;
void Awake()
{
Invoke("EnableComponent", timeOut);
}
void EnableComponent()
{
go.GetComponent<NameOfComp>().enabled = true;
}
}
But it result with error CS0118: TimedObjectEnableComponent.NameOfComp' is a
field' but a `type' was expected. Any help would be appreciated.
Answer by MacDx · Nov 06, 2017 at 10:27 PM
Yes. The problem is exactly what the error describes. You are passing a string where you should be passing type instead. Type is a special class whose instances can represent any object's type and this object (the type one) is NOT the same thing as a string thus the error. The version of the GetComponent method that you are using expects a type, so what you need to do is convert your string into a valid type before passing it.
To convert your string into a type you will need to use a bit of reflection.
void EnableComponent()
{
Type compType = Type.GetType(NameOfComp);
go.GetComponent(compType).enabled = true;
}
Keep in mind that GetType only works for classes in the same assembly. If your class is in another assembly you will also need to specify the name of that assembly. If your class is inside a namespace you will need to specify the namespace as well.
It don't do the job. (Unity 2017.1) I'm getting new error, CS1061: Type UnityEngine.Component' does not contain a definition for
enabled' and no extension method enabled' of type
UnityEngine.Component' could be found. Are you missing an assembly reference?
Also type didn't worked so i modified it to System.Type
But thanks for response!
Yup. $$anonymous$$y mistake I forgot that the field enabled is specific to the Behaviour class (which inherits from Component and is also the class which $$anonymous$$onoBehaviour derives from) but the GetComponent method returns an object of the class Component (who would've known). So just cast the result into a monobehaviour and you are good to go.
Type compType = Type.GetType(NameOfComp);
$$anonymous$$onoBehaviour comp = go.GetComponent(compType) as $$anonymous$$onoBehaviour;
comp.enabled = true;
Also type didn't worked so i modified it to System.Type
Type like I wrote, and System.Type are exactly the same thing. It is only a matter of putting this line: using System; on top of your file to call the Type class implying the System namespace, or you could save that line and write it explicitly like you did.
Regards :)
It actually works now! Thank you for saving my life!