简体   繁体   中英

Using C# IComparer in Unity game engine

I am writing an Edge class for my graph for an A* implementation. I would want to later create a list of Edges and sort them based on edge weights using the IComparer interface.

Below is my implementation of Edge class inside Unity 4.5f

using UnityEngine;
using System.Collections;

public class Edge : IComparer {

    Node destination;
    int weight;

    public Edge(Node destinationNode, int cost)
    {
        destination = destinationNode;
        weight = cost;
    }

    public Node getDestination()
    {
        return destination;
    }

    public int getCost()
    {
        return weight;
    }

    int IComparer.Compare(System.Object a, System.Object b)
    {
        if (((Edge)a).getCost() == ((Edge)b).getCost()) return 0;
        else if (((Edge)a).getCost() > ((Edge)b).getCost()) return 1;
        else return -1;
    }
}

But Unity throws the below error

ArgumentException: does not implement right interface System.Collections.Generic.Comparer`1+DefaultComparer[Edge].Compare (.Edge x, .Edge y) (at /Users/builduser/buildslave/mono-runtime-and-classlibs/build/mcs/class/corlib/System.Collections.Generic/Comparer.cs:86)

I also tried using IComparer<Edge> but it throws error

The non generic type 'System.Collections.IComparer' cannot be used with type arguments

Unity also does not allow me to use IComparable as it does not understand when I try to use it :( it throws

" type or namespace not found "

I don't know whats wrong. Could someone please help me out?

I think Unity expects you to implement IComparable<Edge> (generic version of IComparable, please see http://msdn.microsoft.com/fr-fr/library/4d7sx9hd%28v=vs.110%29.aspx )

This implementation will be really close to yours, except it doesn't need casts (since input types are already some Edge)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM