- Home /
Disable scripts on all gameobjects with tag
Hi!
I need to disable a script on all my "crate" objects in my scene when the player wins. I'm not sure how to do this so I would love any help! Please post your answer in C#.
Thanks!
Answer by Dameon_ · Apr 29, 2014 at 04:26 PM
The easiest way to do this will be to set a boolean variable up called isEnabled in your crate script, and prevent the script from running if it's set to false.
public class ScriptableCrate
{
public bool isEnabled = true;
public void Update()
{
if (isEnabled == false) // Check if this object is enabled
return;
}
}
Then, you use this code to set isEnabled on all crates to false:
public void DisableObjectsWithTag(string tagToUse)
{
GameObject[] taggedObjects = GameObject.FindGameObjectsWithTag(tagToUse);
foreach (taggedObject in taggedObjects)
taggedObject.isEnabled = false;
}
Answer by robertbu · Apr 29, 2014 at 04:24 PM
GameObject[] gos = GameObject.FindGameObjectsWithTag("crate");
foreach (GameObject go in gos) {
go.GetComponent<SomeComponent>().enabled = false;
}
'SomeComponent' should be replaced by the component name (not in quotes) that you want to disable.
It doesn't quite work. I can still use the script even if it says it is disabled.
This is my script I need to disable.
using UnityEngine;
using System.Collections;
public class RemoveBlocks : $$anonymous$$onoBehaviour {
public Color hoverColor;
public static bool isEnabled = true;
void Start () {
renderer.material.color = Color.white;
}
void On$$anonymous$$ouseOver () {
renderer.material.color = hoverColor;
}
void On$$anonymous$$ouseExit () {
renderer.material.color = Color.white;
}
void On$$anonymous$$ouseDown () {
if(isEnabled == true){
Lose$$anonymous$$anager.static$$anonymous$$axBreaks -= 1;
Destroy(this.gameObject);
}
}
}
Disabling a script stops Update() FixedUpdate() and OnGUI() calls, but not much else. The easiest way to disable the On$$anonymous$$ouse* callbacks is to disable the collider as well as the script.
GameObject[] gos = GameObject.FindGameObjectsWithTag("crate");
foreach (GameObject go in gos) {
go.GetComponent<SomeComponent>().enabled = false;
go.collider.enabled = false;
}
If you cannot do that, you might have to go to a solution like @Dameon_ suggested where you have a flag that each callback checks.
Your answer
Follow this Question
Related Questions
disable a script 1 Answer
How can I enable and disable scripts at runtime? 2 Answers
how to disable specific scripts in an array of scripts 3 Answers
Disabling scripts from compiling, but still shows in project pane? 1 Answer
Disabling Scripts 1 Answer