- Home /
How to make a script to add components but be able to change it in inspector
function Start () {
gameObject.GetComponent("Be able to change this").enabled = false;
how would i be able to type... say "ridgidbody" in a slot in the inspector and on start up it adds a ridgid body or i typed "box collider" and it added a box collider insted of makeing a bunch of scripts to do this.
Answer by GameVortex · Jan 28, 2014 at 09:11 AM
This can be done using the normal AddComponent function of GameObject. Declare your public string and set it to whatever type you want it to represent. Use AddComponent(string type) to add the component.
var componentType : String;
function Start()
{
var added : Component = gameObject.AddComponent(componentType);
added.enabled = false;
}
Keep in mind that you will not be able to automatically know in code what type the added Component is so you can only access the Component class variable and functions.
Answer by TropicalTrevor · Jan 28, 2014 at 03:24 AM
You could make an EditorWindow or a custom inspector, but easier solution may be simple script:
You need to make sure you script runs in edit mode by putting @ExecuteInEditMode above the class Then you need a serialized private variable to store if an object was already added by this script (if so you can delete it whenever hte component that it is supposed to add changed).
@SerializeField var createdObject : Object;
Lastly you need a function that only executes in Edit mode by checking if the application is playing and then returning too early
function Update()
{
//only in edit mode
if(Application.isPlaying) return;
//dont add duplicates, only add when name was edited
if( GetComponent(componentName) != null ) return;
if(createdComponent != null)
DestroyImmediate(createdComponent);
try{
createdComponent = AddComponent(componentName);
}except{}
}
see i am not the greatest coder i know its noob thing to ask but would you be so kind to show the whole script so i could learn how it works i know the basics of js but not some this thank you in advance
Your answer
Follow this Question
Related Questions
Add material component to object script-wise 4 Answers
Get GameObject from List based on attached script or assigned name 3 Answers
2D Animation does not start 1 Answer
Does SpriteManger2 can duel with layer's components? 0 Answers
Adds infinite # of components, using GameObject.AddComponent. 4 Answers