I’m trying to enable / disable a script on a different gameObject’s script …
Looked on all the posts on the forum about the subject and tried about everything suggested and nothing works…
Heres the problem :
So to access and enable the script on the GameObject I use: GameObject.Find(the gameObject).GetComponent(the script).enabled = true;
but then I get this : BCE0019: ‘enabled’ is not a member of ‘UnityEngine.Component’.
So on the forums some say to use active instead of enabled… then I get this :
BCW0012: WARNING: ‘UnityEngine.Component.active’ is obsolete. the active property is deprecated on components. Please use gameObject.active instead. If you meant to enable / disable a single component use enabled instead.
sigh
I get : BCW0012: WARNING: ‘UnityEngine.GameObject.active’ is obsolete. GameObject.active is obsolete. Use GameObject.SetActive(), GameObject.activeSelf or GameObject.activeInHierarchy.
Seriously it tells me to use something that is Obsolete , anyways so I use (even if its no longer a component… GameObject.SetActive(),
result : BCE0049: Expression ‘GameObject.Find(GameObject).GetComponent(Script).gameObject.SetActive’ cannot be assigned to.
No surprise there.
So how do you enable / disable a script from another gameObject’s script …??? ty!
Despite being a little surprised, I confirmed that there’s no enabled property in the Component base class! That’s weird, because its descendants usually have such property. Anyway, you can use the typed version of GetComponent instead of the string version:
GameObject.Find("someObject").GetComponent(ScriptName).enabled = true;
ScriptName in this case must be replaced by the script class name, which is the script filename without extension. If the script is “PlayerHealth.js”, for instance, its class is PlayerHealth:
GameObject.Find("someObject").GetComponent(PlayerHealth).enabled = true;
Using the string version of GetComponent is only recommended when the compiler doesn’t know the script class - it has not been compiled yet, is in a different language or will be defined by a string assigned at runtime. If you really need to use the string version, then coerce the type to MonoBehaviour, which is the “mother of all scripts” and has the enabled property:
(GameObject.Find("someObject").GetComponent("ScriptName") as MonoBehaviour).enabled = true;
furic
3
Make sure your script is defined as:
using Unity.Engine;
using System.Collections;
public class MyScript : MonoBehaviour
{
}
MyScript should always be derived from MonoBehavious or any parent class derived from MonoBehavious