- Home /
Affect All Instances Of A Prefab
Hey guys, thanks for taking a look at my question. Basically, I am using the
gameObject.Find("Object").GetComponent(Script).enabled=false
thing. I want to disable a script on all instances of a prefab, but this only affects the main object, not everything.
gameObject.FindWithTag
doesn't work either. To sum up, I would like to find a way to disable a component, or this case a script, on all instances of a prefab. Thank you :D.
please format your code.
Next time you'll post A or Q highlight your code and press 101010 button, it's easier to read.
Ty sdgd for editing XD. Sorry for my improper manners, I am new.
well usually I point to tutorial on the right but today it's not working.
usually I don't edit, because I didn't have that powers before.
Answer by sdgd · Feb 23, 2014 at 12:48 AM
there are a coupple of ways you can do this:
1 is tagging all your your objects a certain prefab.
and than call it:
GameObject[] GOs = GameObject.FindGameObjectsWithTag("TagName");
// now all your game objects are in GOs,
// all that remains is to getComponent of each and every script and you are good to go.
// to disable a components
for (i=0; i<GOs.Length; i++){
// to access component - GOs[i].GetComponent.<BoxCollider>()
// but I do it everything in 1 line.
GOs[i].GetComponent.<BoxCollider>().enabled = false;
}
another method is to use static variables or for your case function.
static void FunctionToDeactivateAllScripts(){
this.enabled = false;
}
now when you call this function from anywhere ALL scripts containing this function will be disabled, because only 1 function exists.
Hmmm, the second option won't work in my case. But the first option, what do you mean by "tag" all my objects. All the objects are instances of a prefab. And where would I put that line of code.
you put that line of code anywhere you want, it'll search entire Hiearchy afaik only active GameObjects.
and by tag I ment in inspector top left you see tag.
default tag is untagged.
to change tag either change tag of your prefab in inspector OR everytime you instantiate a prefab with:
gameObject.tag = "YourTagName";
OFC don't forget to add tags, ...
Oh $$anonymous$$an this saved my life!
I was wondering why my 1st prefab was only being affected by the script. This for loop was the answer!
Thank you sdgd!!!!!
Answer by Kibsgaard · Feb 23, 2014 at 01:05 AM
You could try (C#):
GameObject[] gos = GameObject.FindGameObjectsWithTag("TagOnObjects");
foreach(GameObject go in gos)
{
go.GetComponent<NameOfScript>().enabled = false;
}
If you for some reason need to change it through prefabs, take a look at PrefabUtility.
Answer by ReContraChanfle · Feb 23, 2014 at 03:41 AM
if you disable the script in only one prefab, that affects all other.
something like this:
if(something)
Object(Prefab).GetComponent<Script>().DoSomething();