ICcomparable items cannot get if contained in list...
No other forum questions answer my problem (those that I've seen at least)
I copied this script from the scripting API and changed all the "BadGuy" to "PlayerID" :
using UnityEngine;
using System.Collections;
using System; //This allows the IComparable Interface
//This is the class you will be storing
//in the different collections. In order to use
//a collection's Sort() method, this class needs to
//implement the IComparable interface.
public class BadGuy : IComparable<BadGuy>
{
public string name;
public int power;
public BadGuy(string newName, int newPower)
{
name = newName;
power = newPower;
}
//This method is required by the IComparable
//interface.
public int CompareTo(BadGuy other)
{
if(other == null)
{
return 1;
}
//Return the difference in power.
return power - other.power;
}
}
When a username that hasnt been given a PlayerID (found by their username) it will automatically create the ID for them, stored for the admin to use:
public List<PlayerID> _playerIDs;
void OnChatMsg() {
if (!_playerIDs.Contains(msg.userName){
Debug.log("Success! Creating ID");
}
}
The error I'm receiving is: error CS1503: Argument #1' cannot convert
string' expression to type `PlayerID'
Answer by IgorAherne · Jan 28, 2017 at 12:04 AM
You need linq
using System.Linq;
void OnChatMsg() {
//Look through playerIDs, and find first id such that id.name == ms.userName.
//Returns null if not found (exactly what you would need)
// Notice, SingleOrDefault relies on YOU ensuring there are no identical entries,
// otherwise use FirstOrDefault()
if (_playerIDs.SingleOrDefault(id => id.name == msg.userName) == null){
Debug.log("Success! Creating ID");
}
}
Right, that's a solution. However using a Dictionary for looking up a playername at runtime would be better. Though since we don't know all details this is a valid solution. In the end the question has nothing to do with the IComparable interface.
Your answer
Follow this Question
Related Questions
Rotating Camera on click and drag 0 Answers
How Can I Change General Light Settings With Script 1 Answer
SQL Unity Android 0 Answers
Object orientation remains the same while rotating object 1 Answer