Как упорядочить порядок создания экземпляра сборного дома под родителем в единстве? - PullRequest
0 голосов
/ 09 апреля 2019

Попытка вывести список файлов по расширению * .json. Создание префабов под родителем, но не в порядке. Есть способ обновить список или упорядочить их в порядке возрастания. Цель состоит в том, чтобы загрузить и удалить файлы. Как расположить файлы 1,2, 3,4,5 ... а если есть 10 файлов, то последний сохраненный файл должен оказаться там на 10-м месте под родителем?

Dictionary<int, Button> BtnList = new Dictionary<int, Button>();
public static FileInfo[] info;
GameObject lisobj;

public void ListMap()
{

    panellist.SetActive(true);
    string mainpath = Application.persistentDataPath;
    DirectoryInfo dir = new DirectoryInfo(mainpath);



    info = dir.GetFiles("*.json");


    for(int i = 1;i<=info.Length;i++)
    {
           lisobj = Instantiate(prefabpanellist);
        lisobj.transform.SetParent(Parentcontent);

            number.text = i.ToString();
            mapnamedb.text =info[i-1].Name;

        var button = lisobj.GetComponentInChildren<Button>();
        BtnList.Add(i,button);



    }
    lisobj.transform.SetParent(Parentcontent);

    Dictionary<int, Button>.ValueCollection values = BtnList.Values;

    foreach (Button btn in values)
    {

        btn.onClick.AddListener(() => Deleteinformation());


    }

}

public void Deleteinformation()
{
    var b= UnityEngine.EventSystems.EventSystem.current.currentSelectedGameObject.GetComponent<Button>();


    var mykey=BtnList.FirstOrDefault(x=>x.Value==b).Key;
    Debug.Log("Items are" + mykey);

    string mainpath = Application.persistentDataPath;
    Debug.Log("Name is " + info[mykey - 1].Name);

    //File.Delete(mainpath + info[mykey-1].);
}

Первоначально, когда я сохраняю файл в .json и нажимаю кнопку для Listmap (чтобы показать список файлов - показанный на снимке экрана). Он показывает индекс номер 5 два раза. Также последний сохраненный файл был назван «00000. json ", но он стал первым файлом. Это происходит после того, как я сохраняю его (список файлов), который не обновляется. Когда я нажимаю Listmap, файлы показывают одинаковое число индексов несколько раз. Кажется, что он не обновляется, не уверен. проблема в том, что последний сохраненный файл идет вверху.

1 2

1 Ответ

1 голос
/ 09 апреля 2019

Я установил все это вместе, и теперь это прекрасно работает для меня:

Примечание: я закомментировал все, что не относится к примеру (или то, что вы не добавили в свой код в вопросе)

public class FilesExample : MonoBehaviour
{
    // Start is called before the first frame update
    private void Start()
    {
        ListMap();
    }

    public static FileSystemInfo[] info;

    public void ListMap()
    {
        /*
         * If you already called this before you already have child objects
         * So I would destroy the old ones before instantiating new ones
         */
        //foreach(Transform child in Parentcontent)
        foreach(Transform child in transform)
        {
            Destroy(child.gameObject);
        }

        //panellist.SetActive(true);

        /*
         * preferred to use streamingAssetsPath for testing
         */

        //var mainpath = Application.persistentDataPath;
        var mainpath = Application.streamingAssetsPath;
        var dir = new DirectoryInfo(mainpath);

        info = dir.GetFileSystemInfos("*.json").OrderBy(i => i.CreationTime).ToArray();

        for (var i = 1; i <= info.Length; i++)
        {
            /* 
             * Instead of instantiating I simply created new empty objects
             * just as example 
             */

            //var lisobj = Instantiate(prefabpanellist);
            var lisobj = new GameObject(i + " " + info[i - 1].Name);
            //lisobj.transform.SetParent(Parentcontent);
            lisobj.transform.SetParent(transform);

            // Though I'm sure this should already have the correct order
            // you could still do SetLastSibling to move the 
            // created/instantiated object to the bottom
            lisobj.transform.SetAsLastSibling();

            //number.text = i.ToString();
            //mapnamedb.text = info[i - 1].Name;

            /*
             * NOTE: I would simply do the buttons thing in the same
             *       loop. That saves you a lot of storing and accessing lists
             */

            //var index = i;
            //var button = lisobj.GetComponentInChildren<Button>(true);
            //button.onClick.AddListener(() => Deleteinformation(index));
        }
    }

    public void Deleteinformation(int index)
    {
        Debug.Log("Index is " + index);

        Debug.Log("Path is " + info[index].FullName);

        File.Delete( info[index].FullName);

        // update the scene list
        ListMap();
    }
}

Результат

Файлы на диске упорядочены по имени

enter image description here

Файлы на диске упорядочены по дате создания

enter image description here

результат в Unity, упорядоченный по дате создания

enter image description here

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...