- Home /
enabling and disabling scripts in an array?
Usually, I do
blabla.GetComponent<"script">().enabled = true/false.
But there are many scripts I want to enable and disable at the same time. They are at different gameobjects so I just cant activate/deactivate the gameobject.
I tried to put it in a public array so I can just drag and drop the scripts I want to activate. But the problem is I cant enable or disable it.
public Component[] scripts;
public void Activate()
{
foreach (Component qwe in scripts)
{
qwe.enabled = true;// <-- no ".enabled"
}
}
Is there a better way of activating a bunch of scripts together?
typecast to the name of the class :
public NameOfScriptHere[] scripts;
public void Activate()
{
foreach (NameOfScriptHere qwe in scripts)
{
qwe.enabled = true;// <-- no ".enabled"
}
}
I have different scripts like moveScript, healthScript etc. that I would like to enable and disable together.
Sorry, that wasn't clear. I read as you had the same script on different gameObjects.
I can only suggest inheritance to make them all of the same base class, but there are much smarter people here.
Thanks anyway. I found out the answer already. It should be $$anonymous$$onoBehaviour not Components
public Component[] scripts;
// Update is called once per frame
void Update () {
foreach ($$anonymous$$onoBehaviour qwe in scripts)
{
qwe.enabled = false;
}
wow thanks I was so stuck with this. Certainly that $$anonymous$$onoBehaviour type was a gamechanger. thanks!.
Answer by Pulov · Mar 04, 2015 at 11:19 PM
This script will allow you people to switch betwen enable/disable the components you drag in the array. You can use it for many things as the input key is setable.
using UnityEngine;
using System.Collections;
public class Components : MonoBehaviour {
public Component [] components; //drag your scripts or whatever component you whant to disable here.
private int index;
public KeyCode ActivatorKey;// you can make a multipurpose script by using a editor inputed key, now it is not used change it bye Keycode.T.
//---------------------------------------------------------------------------------------------------------
void Start () {
index = 0;
}
//---------------------------------------------------------------------------------------------------------
void Update () {
Component grayscale;
if (Input.GetKeyDown(ActivatorKey)){
foreach (MonoBehaviour qwe in components)
{
qwe.enabled = !qwe.enabled;
}
}
}
}