James
James

Reputation: 81

Iterate a dictionary of interfaces as specific type

I have a dictionary of string/interface class. I cannot include the fields I need in the interface child-classes, but each of them have the same public variables I need to change.

I want to loop through the dictionary and change them to values within the looping class. I cannot do so, as the interface does not contain those variables.

How should I go about this?

public class MakeAbility : MonoBehaviour
{
public BlockScriptableObject block;

public IDictionary<string, IAbility> abilities_parts = new Dictionary<string, IAbility>();


public Targeting target_manager;

public AbAttack attack;
public AbCast cast;
public AbDefend defend;
public AbDefendOther defend_other;
public AbPotion potion;

private void Start()
{
    abilities_parts.Add("attack", attack);
    abilities_parts.Add("cast", cast);
    abilities_parts.Add("defend", defend);
    abilities_parts.Add("defend_other", defend_other);
    abilities_parts.Add("potion", potion);
}

public void trigger_button()
{
    foreach (var i in abilities_parts.Values)
    {
        i.block_attack_damage = block.attack_damage;
        i.targeting_for_attack = target_manager;
    }



public interface IAbility
{
void Use();
void Enact();
}

public class AbPotion : MonoBehaviour, IAbility
{
public Targeting targeting_for_attack;
public int block_attack_damage = 10;

public void Use()
{

}

public void Enact()
{

}

}

Upvotes: 1

Views: 92

Answers (1)

Franck
Franck

Reputation: 4440

Your properties are NOT properties of IAbility. They are properties of the AbPotion class. You will need an if else statement on the types to set them individually. The thing is, they should have been set before adding to the Dictionary and probably thru the constructor.

public void trigger_button()
{
    foreach (var i in abilities_parts.Values)
    {
        if(i is AbPotion)
        {
            var potion = i as AbPotion;

            potion.block_attack_damage = block.attack_damage;
            potion.targeting_for_attack = target_manager;
        }
        else if(i is AbAttack)
        {
            var attack = i as AbAttack;

            attack.Property1= value1;
            attack.Property2 = value2;
        }
    }
}

Upvotes: 1

Related Questions