- Home /
Syntax for method wich returns generic type (own class)?
Is it somehow possible to put a class component in a method which then checks if it's on the object and returns this component or null? I know how to do it if i just have to return a boolean value, just as described here: http://forum.unity3d.com/threads/check-if-a-gameobject-has-a-certain-script.88484/, but I'm looking for something as requested here, but was never answered: http://answers.unity3d.com/questions/218771/generic-methods-in-unityscript.html
This is what I want to achieve (not working!):
protected T ComponentInRange<T>(float range) {
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, World.maxRange)) {
Transform hitTrans = hit.transform;
if (Vector3.Distance(hit.point, transform.position) < range) {
return hitTrans.GetComponent<T>() as T;
}
}
return null;
}
Comment
Your answer
![](https://koobas.hobune.stream/wayback/20220613180105im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Get Component by T 4 Answers
How Do I deActivate One Sphere ? 1 Answer
differences: generic GetComponent. 3 Answers
Passing Type variable to generic type: Variable not found. 1 Answer
Convert UnityEngine.Component to T 1 Answer