Hello everyone, I’m doing a script in which you can drag and drop any type of component, this script disables him and after some time again enable. Unfortunately I have not found a way to get “ANY” type, certainly it will datatype but I do not know what type.
I imagine something like this
public any dropped;
dropped = this.gameObject.GetComponent<any>();
dropped.SetActive(false);
//After 5.Sec
dropped.SetActive(true)
//Repeat lines 3-5
could anyone help me?
ps. Sorry if some part of the text is unreadable or illogical. I am Czech, and with this text helped me a lot Google Translate.
I would go for generics. Also note that SetActive is for GameObjects, not Component. For Component you can use enabled, but only if the derive from MonoBehaviour (e.g. Scripts). For all others Components I don’t know any way to disable them in the current Unity Version. So you might have to destroy and Add them. You could try this:
IEnumerator genericMethod<T>(GameObject go) where T:Component
{
T dropped;
dropped = go.GetComponent<T>();
if (typeof(T).IsSubclassOf(typeof(MonoBehaviour)))
{
//Scripts
(dropped as MonoBehaviour).enabled = false;
yield return new WaitForSeconds(5);
(dropped as MonoBehaviour).enabled = true;
}
else
{
//Other Components
Destroy(dropped);
yield return new WaitForSeconds(5);
go.AddComponent<T>();
}
}
I think you should describe what you want a bit more.
@LK84’s answer is good but i would assume the generics might not suit your purposes since you are talking about dragging and dropping things. In generics you have to know the types compile time.
Like LK84 said, you don’t need a Component to call SetActive().
You can get any Component with GetComponent(), but if the Component you get is a Transform for example, how would you disable or enable it?
Behaviours are ‘components that can be enabled or disabled’ as Unity docs say
You can get any Behaviour by calling GetComponent() and use the enabled variable.
If you want to be even more specific, you can just get any ‘script’ with GetComponent()