C# GetComponent, component not turning off.

Hello, I’m trying to enable the script ‘Rigidbody First Person Controller’ using c#.
This is my code…

	public void SpawnMyPlayer() {
		Spawnpoint mySpawnSpot = spawnPoint[Random.Range (0, spawnPoint.Length)];
		GameObject myPlayerGO = (GameObject) PhotonNetwork.Instantiate("Player", mySpawnSpot.transform.position, mySpawnSpot.transform.rotation, 0);
		SpectateCam.enabled = false;
		((MonoBehaviour)myPlayerGO.GetComponent("Rigidbody First Person Controller")).enabled = true;

		/*Component comp = myPlayerGO.gameObject.GetComponent("RigidbodyFirstPersonController");
		comp.gameObject.SetActive(true);*/
	}
}

Thanks!

The function Transform.Find is not able to get inactive GameObjects.

GetComponent works the same way. If the component is not enabled, GetComponent won’t be able to get it.

Anyway, make sure the name of your component is correct. Don’t rely on the name in the inspector but the name of the script itself :

(myPlayerGO.GetComponent<RigidbodyFirstPersonController>()).enabled = true;

Make sure you the RigidbodyFirstPersonController is defined in the same namespace of your script. If not add the following line at the top of your script :

using <NameOfTheNamespaceOfRigidbodyFirstPersonController>

Considering your script exact name is “RigidbodyFirstPersonController.cs”, which means component being called “RigidbodyFirstPersonController”, try

myPlayerGO.GetComponent<RigidbodyFirstPersonController>().enabled = true;

By the way, such code may throw an exception, which leads to bit more proper code:

try{
    myPlayerGO.GetComponent<RigidbodyFirstPersonController>().enabled = true;
}catch(System.NullReferenceException e){
    //serve your exception here.
}

I hope it helps.