I need to write a function that grabs a component based on a parameter.
I tried to use string, then GetType and it didn't work.
I tried using MonoBehaviour, but it didn't work. My current version is below. What am I missing?
void move(MonoBehaviour co){
Touch screentouch = Input.GetTouch(0);
Ray ray = camera.ScreenPointToRay(screentouch.position);
if (screentouch.phase == TouchPhase.Began)
{
if (Physics.Raycast(ray, out RaycastHit hitInfo))
{
if (hitInfo.collider.gameObject.GetComponent<co>() != null)
{
set = true;
}
}
}
CodePudding user response:
GetComponent<T>
is a so called generic method.
The generic type parameter T
needs to be a compile time constant type like e.g.
Renderer renderer = someGameObject.GetComponent<Renderer>();
will return an instance of type Renderer
.
var something = someGameObject.GetComponent<ISomeInterface>();
will return an instance of type ISomeInterface
.
The other overloads both GetComponent(Type type)
and GetComponent(string typeName)
both return the most basic type Component
and in order to properly work with it you have to type cast the result afterwards.
Same example would look like e.g.
Renderer renderer = (Renderer) someGameObject.GetComponent(typeof(Renderer));
or
Renderer renderer = (Renderer) someGameObject.GetComponent("Renderer");
So in your case you either know the type you are looking for and should pass that one in or if you want you can make your own method also generic and do
void move<T>()
{
Touch screentouch = Input.GetTouch(0);
Ray ray = camera.ScreenPointToRay(screentouch.position);
if (screentouch.phase == TouchPhase.Began)
{
if (Physics.Raycast(ray, out RaycastHit hitInfo))
{
if (hitInfo.collider.gameObject.GetComponent<T>())
{
set = true;
}
}
}
}