GetComponent gives a null value to a script component

Hey All,

So I’m looking forward to see my silly mistake on this one but I can’t for the life of me get around it.

I am instantiating 2 game objects both with a Player tag, and am able to access them with
GameObject.FindGameObjectsWithTag(“Player”) and change paramters with the same code as below, but when I try GetComponent directly, through player.transform.GetComponent() or through player.gameObject.GetComponent() it keeps giving playerScript a null value (and yes I have tried to initiate it outside of the loop)

Can anyone see what I’m doing wrong here? Thanks!

	void Start () {
		//Instantiate 2 game objects - both have Player class in Player.cs component.
		//Go through both game objects one by one and activate a setter.
		int i = 1;
		GameObject[] playerList = GameObject.FindGameObjectsWithTag("Player");
		foreach(GameObject player in playerList){
			Player playerScript = player.transform.GetComponent<Player>() as Player;
			if(playerScript.getPlayerNumber() == 0){

This script has no errors and it runs just fine (anyway you don’t need to call GetComponent on transform/gameObject, just use player.GetComponent and there’s no need for the direct cast “as Player” because GetComponent already returns a Player object). Your issue is most likely that you have another object in the scene with the tag “Player” which hasn’t the Player component attached, add a debug print to find it:

Player playerScript = player.GetComponent<Player>();
Debug.Log( + " >> " + playerScript);