- Home /
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!
Answer by Hellium · Jun 30, 2015 at 06:46 PM
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>
I made sure the name is the exact name of the script, however I get this error: Assets/$$anonymous$$ultiplayer/SpawnPlayer.cs(18,42): error CS0246: The type or namespace name `RigidbodyFirstPersonController' could not be found. Are you missing a using directive or an assembly reference?
Does the RigidbodyFirstPersonController is defined inside a namespace ?
If so, add using <TheNameOfTheNameSpace>
at the top of your SpawnPlayer script.
Could we take a look at the RigidbodyFirstPersonController.cs file ?
From what I know it isn't defined inside a namespace, though here's the RigidbodyFirstPersonController.cs (It's from the Unity standard assets): http://pastebin.com/6AbFAvGA
Bingo !
namespace UnityStandardAssets.Characters.FirstPerson
Then, add using UnityStandardAssets.Characters.FirstPerson
at the beginning of your SpawnPlayer script.
Answer by Pindwin · Jun 30, 2015 at 06:48 PM
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.
I got this error: Assets/$$anonymous$$ultiplayer/SpawnPlayer.cs(18,41): error CS0246: The type or namespace name `RigidbodyFirstPersonController' could not be found. Are you missing a using directive or an assembly reference?
sorry couldn't reply, was offline since answering. Glad to see you got this sorted out :)