- Home /
Implicit type GetComponent call
I read the following article on MonoBehaviours and abstraction (very interesting BTW). I have difficulties to understand a part of his article, where he seems to implicitly type his generic GetComponent calls. At some point he uses:
GameObject projectile =
(GameObject) GameObject.Instantiate(projectilePrefab, owner.transform.position, Quaternion.identity);
projectile.GetComponent().SetMovement(new LinearMovement());
Later he defines the following extension methods
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
internal static class ExtensionMethods
{
public static T GetAbstract(this GameObject inObj) where T : class
{
return inObj.GetComponents().OfType().FirstOrDefault();
}
public static T GetInterface(this GameObject inObj) where T : class
{
if (!typeof(T).IsInterface)
{
Debug.LogError(typeof(T).ToString() + ": is not an actual interface!");
return null;
}
return inObj.GetComponents().OfType().FirstOrDefault();
}
public static IEnumerable GetInterfaces(this GameObject inObj) where T : class
{
if (!typeof(T).IsInterface)
{
Debug.LogError(typeof(T).ToString() + ": is not an actual interface!");
return Enumerable.Empty();
}
return inObj.GetComponents().OfType();
}
}
he then calls these methods this way:
GetInterface().Open();
I don't understand how this is possible, I've never seen any GetComponents call without specifying the type between . He seems to implicitly define the type "Any type with a specific method", but when I try something similar it does not compile. I get the following error:
Constraints are not allowed on non-generic declarations
Is there a mistake in the article or am I not understanding what is going on?
Your answer
Follow this Question
Related Questions
HasComponent 4 Answers
How to GetComponent from Class that uses Generics 1 Answer
Getting variables by their names? 3 Answers
Getting all scripts attached to a gameObject (Problem) 1 Answer
Multiple Cars not working 1 Answer