GetComponent with multiple instances of same script on object

Hi there,

I was wondering if there was a way of identifying a specific script on a gameObject via one of it’s variables. Here’s my situation.

I have a gameObject in my scene called “Players”.

Attached to this otherwise empty gameObject, I attach 4 copies of the same script called ‘PlayerScript’. The function of Playerscript is to keep track on individual stats for each of the players in my game such as health, score etc. I don’t want to have multiple scripts per player, or even scripts which inherit from one script. One of the variables in PlayerScript is a public int known as PlayerID. It is the only variable which acts as a unique identifier for each script.

When I use GetComponent in an example such as:

public GameObject playersObject; (assign in inspector)
public PlayerScript exampleScript;

void Start(){
exampleScript = playersObject.GetComponent();
}

Can I do it in such a way that I can identify the specific script I want, such as the one with the PlayerID variable being equal to 3?

How might I go about doing this (aside from having multiple objects and 1 script per object)?

You can use GetComponents to get all of them and then loop through and detect which is which by the PlayerId.

public GameObject playersObject;
public PlayerScript exampleScript;

void Start() {
    PlayerScript[] playerScripts = playersObject.GetComponents<PlayerScript>();
    foreach (PlayerScript playerScript in playerScripts) {
        if (playerScript.PlayerId == 3)
        {
            exampleScript = playerScript;
        }
    }
}

But realistically that is pretty inefficient especially since you may be calling individual players often. I would suggest creating a Hashtable/Dictionary of PlayerScripts that is initialized on some other object’s Start function (perhaps a GameManager script?) that has all of these scripts. Basically this Hashtable/Dictionary would associate each unique PlayerId to its appropriate PlayerScript.