Best way to pass variables between instantiated/colliding objects?

I’m making a small FPS where I run into this a lot - say I got a GameObject instantiating from my weapon every time it fires, with a ‘Projectile’ class. My weapon class has damage specified, and I wish to pass this along to a variable in the Projectile class.

Likewise, when the projectile hits an enemy, this is handled by the enemy class (to avoid crowding the projectile class with events for every thing it can hit) - so I need a way to pass the damage variable along to the enemy class.

Currently I do this with a simple GetComponent, in the Weapon class:

GameObject newProjectile = Instantiate(projectile, firePosition.position, firePosition.rotation);
newProjectile.GetComponent<Projectile>().damage = damage;

And when hitting an enemy, in the Enemy class:

void OnTriggerEnter (Collider col)
    {
        if(col.gameObject.tag == "projectile")
        {
            health = health - col.GetComponent<Projectile>().damage;

But I’d prefer not to have to use GetComponent for performance reasons - is there a more proper way to do this?

If you don’t want to use GetComponent, then you are going to need the component cached somewhere. A way to do this when firing projectiles it to use pooled objects that you have already added in the scene to the inspector. Something like an array of projectiles:

public Projectile allProjectiles

Then use a counter to identify the projectile you want to use.

allProjectiles[cntr].damage = damage