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)” ?
1 Answer
1You can use a LINQ method “Any” and a “is” operator for the condition.
Here are a couple of references:
- Enumerable.Any Method (System.Linq) | Microsoft Learn
- The `is` operator - Match an expression against a type or constant pattern | Microsoft Learn
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 { /* ... */}