Getting "parent" script data

I have three classes which correspond to three different game objects.

  • GoodGuy
  • BadGuy
  • Weapon

When a GoodGuy uses the Weapon it does damage to the BadGuy. The amount of damage is determine by the GoodGuy. This is so that different GoodGuy instances can do different amounts of damage. When the Weapon object hits the BadGuy it does the damage. I’m trying to figure out how to get the damage variable from the GoodGuy instance in the Weapon class.

You can do this by giving the GoodGuy class a reference to the Weapon object. Then the GoodGuy code can set the damage on the Weapon, like this:

public class GoodGuy : MonoBehaviour
{
    [SerializeField] private Weapon weapon;
    [SerializeField] private float damage;

    // You can call this in Awake() or Start().
    public void ConfigureWeapon()
    {
        weapon.damage = damage;
    }
}

Of course, there are many other ways of doing this, depending on what your code looks like and what you intend to do. It is hard to provide a more specific answer without more detail about your design.

Hope this helps!

@timoffex

I appreciate the help. That does help quite a bit. So that is what My GoodGuy class looks like (more or less). I’ll post the Weapon script below. I should be more specific. It’s really a projectile class. So while your solutions works perfectly for something like a sword, it doesn’t work for something like a gun with bullets (that needs to be instantiated on command and call the GoodGuy’s getDamage() method or something). I realize I could set the damage via the Projectile game object. But I would rather set it with the GoodGuy so that I can reuse the game object with different characters and change the damage per GoodGuy. Does this add clarity?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Projectile : MonoBehaviour
{
    [SerializeField] float _currentSpeed = 0;
    float _damage;

    public void setDamage(float damage) {
        print("Setting damage: " + damage);
        _damage = damage;
    }

    private void OnTriggerEnter2D(Collider2D otherCollider) {

        // Reduce Enemy Health
        var enemy = otherCollider.GetComponent<Enemy>();
        enemy.takeDamage(_damage);
    }
}