- Home /
Other
How to add a script to an gameobject when it is instanced in the scene view ?
How do I go about adding a script component to any gameobject instanced in scene view .
i.e If i create a new Cube or a point light, a particular script will get attached to it .
I ave been looking at AssetPostprocessor but i did not find an answer there . the closest thing was using ModelImporter to get between the import process of models . but this will only work for models , models imported into unity.
Those you mention get component because they are prefabs. So are you needing prefabs?
prefabs are not the main concern now . I'm mean that is i click GameObjecy/3D Object/Cube and instance a cube , I want a particular script (custom script) to be added to it.
sorry if i'm being too unclear or not understanding something
You can either add a script manually, by code, or by using a prefab. To my knowledge there is no way to automatically attach a script to a freshly instanced cube. I don't really see the need either since that's what prefabs do
Answer by pako · Jun 07, 2015 at 07:24 PM
You can use GameObject.AddComponent:
http://docs.unity3d.com/ScriptReference/GameObject.AddComponent.html
For example when the following script is attached on GameObject1 in the scene, when it is clicked, it will first create a cube primitive in the scene, and then add a CustomMonobehaviour to it:
public class AddBehaviour : MonoBehaviour {
// Use this for initialization
void OnMouseDown() {
GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube)
cube.AddComponent<CustomMonoBehaviour>();
}
}
This seems to be what you want.
I meant that; when if i click GameObjecy/3D Object/Cube and instance a cube , I want a particular script (custom script) to be added to it.
sure this method would work but than i could just drag the scripts on the objects too.
I only had to change Start() to On$$anonymous$$ouseDown() in my answer to adjust it to your new info. Now, whenever the GameObject/3D Object/Cube with this script gets clicked to instance a cube, it will add the custom script e.g. "Custom$$anonymous$$onoBehaviour.cs" to the instanced cube.
I use a public variable 'go' as the gameObject where the custom script is added, and also I don't show the instantiation code, because this is an example. In your actual code, you just use the variable that holds an instance of the GameObject you instantiate, ins$$anonymous$$d of 'go' in the example.
I edited my answer, yet again, to include cube creation code as well, just in case my answer was still not clear.