- Home /
Adding Script to an "Instantiated" Prefab?
Ok I am sure I am forgetting to do something dumb, but I have a folder full of prefabs that gets created. When I Instantiate them, I want to add a script to them.
for example:
Instantiate(myPrefab, position , rotation);
prefab.AddComponent<myScript>();
This loads the object, but it does not add my script. It gives me an error that says:
Can't add component 'MonoBehaviour' to myPrefab because the game object is a generated prefab and can only be modified through an AssetPostprocessor. UnityEngine.GameObject:AddComponent()
Is there any way to add these scripts to prefabs on the fly without using AssetPostprocessor?
Thanks in advance
Answer by DocteurCox · Jun 26, 2013 at 08:37 PM
GameObject go = Instantiate(myPrefab, position, rotation) as GameObject;
go.AddComponent<myScript>();
That shoult do the trick. Instantiate returns the new instance of your prefab in your scene. myPrefab is the prefab itself -> an editor thing.
Hope it helps :)
Your answer
![](https://koobas.hobune.stream/wayback/20220613104933im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Null Reference Exception on instantiated object's script. 2 Answers
How I can get an instace of a material, created in a project panel 1 Answer
Instantiating a Rigidbody instead of a GameObject 1 Answer
Accessing component of a single prefabs' instance. 0 Answers
Get Component on Instantiated Object 1 Answer