- Home /
Editor Script with for loop
So this is part of my code right now:
prefabamount = EditorGUILayout.Slider("Amount", prefabamount, 1, 99);
GameObject[] worldfab = new GameObject[(int)prefabamount];
int[] worldId = new int[(int)prefabamount];
scrollPosition = EditorGUILayout.BeginScrollView(scrollPosition);
for (int i = 0; i < (int)prefabamount; i++)
{
GUILayout.BeginVertical();
worldfab[i] = EditorGUILayout.ObjectField("Prefab", worldfab[i], typeof(GameObject), true) as GameObject;
worldId[i] = EditorGUILayout.IntField("ID", worldId[i]);
GUILayout.EndVertical();
}
EditorGUILayout.EndScrollView();
but everytime I change the prefab in the editor, it changes back to its null value. I think I know what the problem is, but I don't know how to solve it. Does anybody have an idea?
Answer by Halfbiscuit · Aug 03, 2016 at 10:33 AM
This line:
GameObject[] worldfab = new GameObject[(int)prefabamount];
is wiping the array every time, setting all values to null.
What you can do instead is store the 'worldfab' variable outside the function as a member variable then when you need to adjust the size do this:
GameObject[] temp = new GameObject[worldfab.Length];
int count = Mathf.Min(temp.Length, (int)prefabamount);
for(int i = 0; i < count; i++)
{
temp[i] = worldfab[i];
}
worldfab = new GameObject[(int)prefabamount];
for(int i = 0; i < count; i++)
{
worldfab[i] = temp[i];
}
You will need to do something similar with the int array.
You could always use a list instead then just add or remove entries as necessary.
Your answer
Follow this Question
Related Questions
Create varying numbers of gameObjects/prefabs in sceneview? 0 Answers
Edit an object in isolation quickly, as in the new Prefab Mode 0 Answers
Reordable List in a window 1 Answer
Editor GUI Foldout header style customization 0 Answers
Is it possible to detect drag and drop in hierachy window? 0 Answers