- Home /
Is this supposed to happen to scripts added to prefabs?
I wrote a program to add a script to a prefab. I kept running and stopping the scene to test variables of other things. After a while, my games fps dropped to 3fps and the prefab had many scripts.
I was just wondering is this intentional that the instantiation of a prefab applys changes each time a script component is added? What is a potential use of this feature?
I got rid of the scripts by adding a line to destroy the added script if there. I could have prevented this by checking if the game object already had the script attached.
Answer by asafsitner · Dec 28, 2013 at 09:23 AM
You basically solved your own problem.
This behavior is intentional - your program just kept adding these script components to the source prefab instead of the instantiated game object, so each new instance had all of them attached.
Here is my code. How would I add it to the instantiated gameobject ins$$anonymous$$d of the source prefab?
var s : String = "";
var all : GameObject[] ;
function Start ()
{
boo = true;
all = Resources.FindObjectsOfTypeAll(GameObject) ;
for( var o : GameObject in all)
{
s = o.name;
if( s.Length <= 4 || String.Concat( s[0] , s[1] , s[2] , s[3] ) != "Bone")
{
if(o.renderer && o.gameObject.GetComponent(fm) == null ) // && PrefabUtility.GetPrefabType(o) != PrefabType.$$anonymous$$odelPrefab )
{
//print(PrefabUtility.GetPrefabType(o));
o.AddComponent(fm);
}
}
}
}
On what game object is this script located and when exactly is it supposed to add the component?
It is attached to a gameobject already in the scene. It adds the component when the function Start() is called.
Why not have this piece of code in the same place you instantiate your prefabs?
I have lots of stuff in the scene (that are not necessarily prefabs). I just noticed this property and thought it was weird and possibly a bug. I don't use code to instantiate some prefabs as well.
The whole point of this interaction was to change the materials of all game objects in a scene. I did this successfully. I guess you answered my question. Thanks.
Your answer
![](https://koobas.hobune.stream/wayback/20220613125020im_/https://answers.unity.com/themes/thub/images/avi.jpg)