- Home /
How to check if a list of class contains a class rather than an instance of a class?
Using c#. If I have a class FireClass that inherits from SpellClass. How do I check if a List of SpellClass contains ANY instance of FireClass rather than a specific instance of FireClass as with "GameManager.Instance.AbilityDB.Contains(passedSpellClass)" ?
Answer by Quickz · Apr 12, 2020 at 07:42 PM
You can use a LINQ method "Any" and a "is" operator for the condition.
Here are a couple of references:
https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.any?view=netframework-4.8
https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/is
Here's an example:
using System.Linq;
using System.Collections.Generic;
using UnityEngine;
public class TestScript : MonoBehaviour
{
public List<Spell> spells = new List<Spell>();
private void Start()
{
if (HasSpellOfType<Fire>())
{
Debug.Log("Fire!!!");
}
}
public bool HasSpellOfType<T>() where T : Spell
{
return spells.Any(x => x is T);
}
}
public class Fire : Spell { /* ... */}
public class Spell { /* ... */}
Your answer
Follow this Question
Related Questions
How to store a list of GameObjects with all components (scripts, colliders etc) 0 Answers
Get a List of the declared objects in a class 1 Answer
Button to change list highlighted in editor 0 Answers
Problem with swithing weapons in a list of scriptable objects 1 Answer
How can I destroy my Instance without renaming it? 2 Answers