- Home /
Populating object fields in a loop - editor scripting
Hello, I am creating a custom editor window in which I want the user to be able to populate. The window currently looks like this (messy I know):
I want the user to be able to change to monoscript field from "PositionChange" to any other monoscript. The problem is that these object fields are clearly created in a loop - and if I put the object field with this code for example:
MonoScript transformationFunc = EditorGUILayout.ObjectField(transformationFunc, typeof(MonoScript), true) as MonoScript;
it won't let the user change the field because every time the window is drawn in OnGUI() the field is instantiated again. I tried using a dictionary and create "empty" monoscript objects for every field I know will appear in the window, but the only way to retrieve a monoscript from that dictionary was via the method "TryGetValue", and I couldn't figure out how to make the monoscript field affect the dictionary field using that function.
Any suggestions on how to let the user succesfully change this field? Thanks
p.s - the quantity and names of these fields of course are not known in advance because they depend on the prefab entered by the user (in the screenshot-Cylinder)
Answer by YoucefB · Sep 26, 2017 at 09:45 AM
@erap129 A way to do this would be to create a List of MonoScript then populate it in a for loop. and to get a Script just use its index.
Here is a simple example:
List<MonoScript> monoscripts = new List<MonoScript> (); //List of scripts
int capacity = 50; //how many fields
public void myMonoScriptsLoader(){
capacity = EditorGUILayout.IntField ("Capacity",capacity);
capacity = Mathf.Max (0, capacity);
//add any new fields
for (int m = monoscripts.Count; m < capacity; m++)
monoscripts.Add (new MonoScript());
//remove extra fields
for (int m = capacity; m < monoscripts.Count; m++)
monoscripts.RemoveAt (monoscripts.Count-1);
for (int m = 0; m < monoscripts.Count; m++) {
Rect r = EditorGUILayout.BeginHorizontal ();
// delete a field
if (GUI.Button (new Rect(r.width,r.y,r.height,20),EditorGUIUtility.Load("icons/vcs_delete.png") as Texture2D)) {
monoscripts.RemoveAt (m);
m--;
capacity--;
continue;
}
//display the field
monoscripts[m] = (EditorGUILayout.ObjectField ("monoscript #"+(m+1),monoscripts[m], typeof(MonoScript), true,GUILayout.Width(200)) ) as MonoScript;
EditorGUILayout.EndHorizontal ();
}
}
Your answer
Follow this Question
Related Questions
Is there a way to get all editable fields of a component in a script? 2 Answers
Dynamic content in custom EditorWindow 1 Answer
Acces monobehaviour script from editor script 2 Answers
MethodInfo.Invoke() throwing ArgumentException: failed to convert parameters 1 Answer
Text in custom editor is displayed/rendered with boxes around characters... 2 Answers