Search Unity

Error with generics ("there is no boxing conversion or type parameter conversion")

Discussion in 'Scripting' started by hamberge, Sep 26, 2018.

  1. hamberge

    hamberge

    Joined:
    Aug 30, 2015
    Posts:
    36
    I have a method called:

    public bool IsCellOccupied<T>(Vector2Int cellToCheck) where T : IGridMapAble


    I have the following method call:

    IsCellOccupied<GridTransform>(clickedCell)


    I am getting the error:

    The type 'GridTransform' cannot be used as type parameter 'T' in the generic type or method 'GridMap.IsCellOccupied<T>(Vector2Int)'. There is no boxing conversion or type parameter conversion.

    GridTransform is declared as a class that implements IGridMapAble. I can't figure out why I am getting this error or how to fix it. It seems to me that since GridTransform implements IGridMapAble, there should be no issue, since the method constrains its generic type to IGridMapAble, but I am obviously wrong. Can anybody help me with this?

    Thanks!
     
  2. AdrianoVerona_Unity

    AdrianoVerona_Unity

    Unity Technologies

    Joined:
    Apr 11, 2013
    Posts:
    317
    hi. Can you share your Editor.log?

    Also, maybe share the definition of GridTransform class

    AFAICS this should work
     
  3. BlackPete

    BlackPete

    Joined:
    Nov 16, 2016
    Posts:
    970
    Is that the only error you're getting? Or could there be another error that's preventing the compiler from building the GridTransform class?
     
  4. hamberge

    hamberge

    Joined:
    Aug 30, 2015
    Posts:
    36
    Nevermind, I was doing something silly. The method that was calling

    IsCellOccupied<GridTransform>(clickedCell)


    was declared as a generic method like this:
    public GridTransform GetObjectAtWorldPoint<GridTransform>(Vector3 mouseWorldPosition)


    which was really not what I meant. The name of the type parameter to GetObjectAtWorldPoint (which was GridTransform) was more local in scope than the name of the declared class GridTransform. Thus when I made the call to IsCellOccupied, I was using the completely generic, undefined, local type parameter GridTransform, which of course does not necessarily implement IGridMapAble. I just made the method not generic anymore:

    public GridTransform GetObjectAtWorldPoint(Vector3 mouseWorldPosition)


    since the generic parameter is not necessary, since the method necessarily uses the type GridTransform. This fixed the problem in the call to IsCellOccupied.

    Thanks for confirming that my understanding of constraints was correct, though!