Hey need some help.
Been stuck on this for hours.
Few answers found are for obsolete methods or don’t work.
I am writing an ui helper and have a method that creates Text gameobjects and I want to be able to pass ui Scripts, classes, as a variable to add to the Text gameobject with .addcomponent()
- How do you setup a class, to be used as component, as parameter in a method:
void myMethod(<class as parameter?>)
{
..
}
- How do I use the argument as T:
exampleobj.addcomponont<parameter argument>();
1 Like
I don’t have documentation in front of me, but it looks something like this:
public class Whatever <Type>{
private void myMethod(Type objectName){
}
}
Then you can do this…
Whatever<Jerry> blablabla = new Whatever<Jerry>();
Jerry jerry = new Jerry();
blablabla.myMethod(jerry);
I hope that answers your questions
AddComponent also has a non-generic version. you can write your method as a generic or as a function that accepts a Type as the parameter, or both if you want to cover your bases.
This is an Extension method I made a while back Requires a component variable to be set. If its not it’ll add and cache that variable.
public static T RequireComponent<T> (this UnityEngine.Component source, ref T component)
where T:UnityEngine.Component
{
if(!source)
throw new System.ArgumentNullException("source", "The component from where you are calling this extension method is null, cannot ensure component is set");
var componentType = typeof(T);
if(!component) component = (T)source.GetComponent(componentType);
if(!component) component = (T)source.gameObject.AddComponent(componentType);
return component;
}
you can then use it as so:
private Image myImage;
...
this.RequireComponent<Image>(ref myImage).color = Color.white;