Referencing classes without adding them as components?

Hi there -

I’m trying my hand at coding in a way that’s both modular and intuitive. It’s a simple game where the player and the enemies have can equip different weapons (e.g., a sword and an axe), with each weapon having a different damage type (e.g., piercing for the sword, slashing for the axe, etc).

The idea is to be able to simply drag the corresponding weapon script to the player/enemy GameObject - then the combat script will correctly use the weapon “attached” to the GO when the attack method is called.What I’d like to be able to do is indicate in the weapon script that the damage being dealt is of a certain type (slashing, piercing, and crushing) without dragging and dropping the damage type scripts into the hierarchy.

In the long run, I’d like the game to determine attack outcomes based on the interaction of the attack type, the weapon wielded, and the enemy (e.g., a sludge would be extremely vulnerable to a fire magic attack, but nigh on invulnerable to a piercing attack). This is why I’d like to spell out damage types as different classes.

First, I created the Weapon class:

public class Weapon : MonoBehaviour {

    public string itemName;
    public Damage damageType;
    public int damageAmount;

}

I then created Axe and Sword classes that inherit from Weapon:

public class Sword : Weapon {

    void Start () {
        itemName = "Sword";
        damageType = FindObjectOfType<Slashing>();
        damageAmount = 3;
    }
}

I also created the Damage class…

public class Damage : MonoBehaviour
    {
    public string damageName;
    }

…which Slashing, Piercing, and Crushing all inherit from:

public class Slashing : Damage {
    void Start () {
        damageName = "Slashing";
             }
}

Finally, in the Player class, I have the following method:

    public void AttackEnemy(Enemy target)
        {
        Weapon weapon = GetComponent<Weapon>();
        target.ReceiveDamage(weapon.damageAmount, weapon.itemName, weapon.damageType.damageName);
        }

Now, this is where I run into trouble. Sure, the above works as long as I attach Slashing, Crushing, and Piercing to a GameObject somewhere in the hierarchy. However, I feel that there’s got to be a more elegant way of doing it, one that would allow me to make use of the different damage types without having to add them in the hierarchy as components.

How exactly do I go about accomplishing that? I feel like the solution is probably something really simple and is likely a fundamental of C#/Unity that I’m missing - but I just can’t seem to figure it out.

Cheers,
George

I would recommend looking at this -

I’m sure it’s pretty much what you are looking for.

2 Likes

You can also remove the MonoBehaviour inheritance and mark the class as serialisable. Then you can set up instances directly in the inspector.

1 Like