Is there any way to switch (enabled/disabled) a script that is in another GameObject ?
GameObject.Find("/MyGameObject").GetComponent("MyScript").enabled = false; won't work because the script dont have a enabled attribute.
Thanks in advance
Is there any way to switch (enabled/disabled) a script that is in another GameObject ?
GameObject.Find("/MyGameObject").GetComponent("MyScript").enabled = false; won't work because the script dont have a enabled attribute.
Thanks in advance
Scripts attached to objects do have an enabled attribute, in fact. So what you have should work fine assuming there is a script actually attached.
--Eric
@Ricky: If you're using C# (which I'm assuming since you're using Visual Studio), you can't use the code as written in the question since GetComponent returns a Component object, which does not have "enabled".
If you cast it to your specific type, you can use enabled. (This also applies to strict javascript for unity iPhone).
GameObject.Find("MyGameObject").GetComponent<MyScript>().enabled = false;
or
MyScript myScript = GameObject.Find( "MyGameObject" ).GetComponent( "MyScript" ) as MyScript.
myScript.enabled = false;
(As an aside, using `.Find()` is really slow, so prefer to hook up connections ahead of time with public fields on your scripts.)
If you are getting a NullReferenceException you are getting a null returned from the Find or the GetComponent functions.
You should check that the object exists and can be found by that name and that it has a script called MyScript attached.
@Tetrad Thanks man! Was stuck on this one, your solution worked perfectly. I’m new to programming as well. Appreciate the help.
I also have this issue. Also, the Visual Studio compiler claims there is no such thing as ".enabled". I do not get null reference exception, I get "'UnityEngine.Component' does not contain a definition for 'enabled'."
Please help!