Reference a script you might not know the name to

I have two player characters. Both of them have their own movement script attached to them (they move drastically differently). They both have the same health bar, and can die in the same way.

When either player runs into a specific collider, it calls Death(). The Death function should disable the corresponding movement script.

For a single player, it’s pretty easy. Reference the movement script as an object, then disable the object.

public class PlayerHealth: Monobehavior {

  PlayerMovementScript movement;
  bool dead;

  void Start () {
    movement = GetComponent<PlayerMovementScript>();
  }

  void Dead () {
    movement.enabled = false;
  }
}

However, if I have multiple players, how do I dynamically reference the two different scripts, depending on the object it is attached to? I tried something like this:

public class PlayerHealth: Monobehavior {

  bool dead;

  void Start () {
    if (this.name == "Player1") {
      Player1MovementScript movement = GetComponent<Player1MovementScript>();
    }
    if (this.name == "Player2") {
      OtherPlayerMovementScript movement = GetComponent<OtherPlayerMovementScript>();
    }
  }

  void Dead() {
  // This doesn't work because movement was declared in Start ()
  movement.enabled = false;
  }
}

However, since I have declared the movement variable inside the Start function, I can’t use it elsewhere.

How can I dynamically declare a reference to a script that might have more than one name?

Like @TreyH mentioned, you probably want to use an interface. Below, I made an IMovementScript interface that just has an “enabled” property you can get and set. You need to make sure your movement scripts implement this interface. Then when you use it in your PlayerHealth script, you need to declare it as a class variable if you want to use it across functions. It looks something like this:

public interface IMovementScript
{
    bool enabled { get; set; }
}

public class Player1MovementScript : MonoBehavior, IMovementScript
{
    // ...
}

public class OtherPlayerMovementScript : MonoBehavior, IMovementScript
{
    // ...
}

public class PlayerHealth : MonoBehavior
{
    IMovementScript movement;
    bool dead;

    void Start () 
    {
        if (this.name == "Player1") 
        {
            movement = GetComponent<Player1MovementScript>();
        }
        if (this.name == "Player2") 
        {
            movement = GetComponent<OtherPlayerMovementScript>();
        }
    }

   void Dead() 
   {
       movement.enabled = false;
   }
}