How to access scripts other than by name.

I'm very new to Unity, and for the most part game creation. Even so, this is such a simple issue I feel kind of dumb for not being able to solve it haha.

I have a stats script attached to each of my game objects that keeps track of things like health, mass, damage, etc. It also holds special functions that are for each instance of that object. Then I have a weapon, say a lazer gun. That lazer needs to access the health variable in that stats script. The problem is, that stats script is a different script in every single object I have. For instance, I have PlayerShipStats, or JunkBlockStats, etc.

I can't use `getComponent` because the lazer also needs to be able to access `getComponent` as well. Or, any other number of objects.

Is there an easy way to do this? If not, should I just make one really long script called "Stats" and condense them all? It seems terribly unorganized... Thank You for the help, or just reading at all really.

A few ways come to mind. You could create a stats class or interface which your individual items inherit from or implement, or you could messages.

(the following is off-the-cuff code for illustration)

e.g. inherit from base class

class StatItem : MonoBehaviour
{
  public abstract void AddHealth( int delta );
}
class PlayerShipStats : StatItem
{
  int health = 10;
  public override void AddHealth( int delta ) { health += delta; }
}

And to use it:

StatItem stat = target.GetComponent<StatItem>();
stat.AddHealth( -10 );

e.g. implement interface

interface IHealth
{
  public void AddHealth( int delta );
}
public PlayerShipStats : MonoBehaviour, IHealth
{
  public void AddHealth( int delta ) { health += delta; }
}

And to use it:

IHealth stat = target.GetComponent<IHealth>();
stat.AddHealth( -10 );

e.g. SendMessage

void AddHealth( int delta ) { health += delta; }

And to use it:

target.SendMessage( "AddHealth", -10 );