(){ T g...">

Type "T" cannot be used as a parameter of type "T" in a generic type or method

I have the following method:

protected T AttachComponent<T>(){ T gsComponent = gameObject.GetComponent<T>(); if(gsComponent == null){ gsComponent = gameObject.AddComponent<T>(); } return gsComponent; } 

The following error appears in the AddComponent line:

 The type 'T' cannot be used as type parameter 'T' in the generic type or method 'GameObject.AddComponent<T>()'. There is no boxing conversion or type parameter conversion from 'T' to 'UnityEngine.Component'. 

I'm not sure what I can do to fix this error, why can not I do this?

+5
source share
1 answer

The problem is that the AddObject method returns Component . You need to tell the compiler that your T is actually a component type.

Attach a general constraint to your method to ensure that T Component s

 protected void AttachComponent<T>() where T : Component { // Your code. } 
+13
source

Source: https://habr.com/ru/post/1245502/


All Articles