- Home /
Disable all scripts on gameobject excluding the one calling for disable
Trying to make it so this script will disable all other scripts on a gameobject until the right conditions are met, in this place the conditions are stored in a playerpref, so long as the playerpref != 1 I want all scripts (excluding this one) to be disabled.
public string playerPrefName;
void Start ()
{
if(playerPrefName == null)
{
Debug.Log("Didn't Specify PlayePref");
}
}
void Update ()
{
if (playerPrefName != null)
{
if (PlayerPrefs.GetInt(playerPrefName) == 0)
{
MonoBehaviour[] comps = GetComponents<MonoBehaviour>();
foreach (MonoBehaviour c in comps)
{
if (c.name != this.name)
{
c.enabled = false;
}
}
}
else
{
MonoBehaviour[] comps = GetComponents<MonoBehaviour>();
foreach (MonoBehaviour c in comps)
{
c.enabled = true;
}
}
}
}
}
The problem comes from here
foreach (MonoBehaviour c in comps)
{
if (c.name != this.name)
{
c.enabled = false;
}
}
I tried doing if (c.name != this.name) to stop the script calling itself but it seems like saying "this.name" calls the name of the current c and not the name of the script therefore nothing gets disabled.
Answer by Vicarian · Jul 01, 2017 at 06:52 AM
The name
property in MonoBehaviour returns the name of the GameObject to which a Behaviour is attached. You'd have to hold a reference to the disabler script or check its type as you loop over the other Components. So, assuming the type of your MonoBehaviour is called Disabler, you'd do something like this:
foreach (MonoBehaviour c in comps)
{
if (c.GetType() != typeof(Disabler))
{
c.enabled = false;
}
}
The reason this works is due to a property of C# called polymorphism. You may treat derived classes as their base class and just use a differentiator (a subtype) to take specific actions against that type. Similarly, an initializer:
MonoBehaviour m = new Disabler();
works in base C#, but not in Unity due to constraints on MonoBehaviour constructors imposed by the Engine. However, if you use vanilla classes in your games (which happens occasionally, depending on design) this is a pretty powerful tool to add to your toolbox.
If you're not comfortable with polymorphism, you can use the aforementioned reference route, like so:
Disabler d = GetComponent<Disabler>();
foreach (MonoBehaviour c in comps)
{
if (c != d)
{
c.enabled = false;
}
}
Accomplishes the same thing, but at the small expense of a small amount of memory getting allocated to hold a reference to the type (around 64 bits for a pointer, I think). Additionally, I think you also pay a performance hit because I'm fairly certain GetComponent uses Reflection to differentiate types. It's a hunch, so don't quote me on that. I'm not a Unity engineer.
Answer by omerselman · Jul 01, 2017 at 08:57 AM
public MonoBehaviour[] disabledOnes;
public void Update(){
if (disabledOnes.Length > 0)
{
foreach (MonoBehaviour disableThis in disabledOnes)
{
disableThis.enabled = false;
}
}
}