Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Scan files for image then assign image to buttons

Discussion in 'Scripting' started by kityanlam3, Jun 14, 2016.

  1. kityanlam3

    kityanlam3

    Joined:
    Feb 2, 2016
    Posts:
    41
    I have a series of folders in a directory called furniture. Then the folders are called chair, sofa and so on. Inside each folder there is an image of that object. Example, chair has an image of a chair. What I want to do is to dynamically create buttons for each folder and then assign the image inside each folder to that button. I've already done the buttons.

    Code (CSharp):
    1. for (int i = 0; i < list.Count; i++)
    2.         {
    3.             int index = i;
    4.             GameObject btn = (GameObject)Instantiate(Button);
    5.            
    6.             btn.transform.SetParent(canvas, false);
    7.             btn.GetComponentInChildren<Text>().text = Path.GetFileNameWithoutExtension(list[i]);
    8.             Button b = btn.GetComponent<Button>();
    9.             b.onClick.RemoveAllListeners();
    10.            
    11.             b.onClick.AddListener(() => spawngroundfurniture(index));
    12.             btn.GetComponent<RectTransform>().anchoredPosition = new Vector2(0, 0);
    13.  
    14.         }
    It works perfectly but then I came into the problem of how am I going to tell the program whether the image belongs to the chair folder or the sofa folder.

    Here's the code that I use to scan the folders.

    Code (CSharp):
    1. string[] fileEntries = Directory.GetFiles(targetDirectory, "*.obj", SearchOption.AllDirectories);
    2.         List<string> list = new List<string>();
    3.        
    4.         foreach (string fileName in fileEntries)
    5.         {
    6.             string ext = Path.GetExtension(fileName).ToLower();
    7.            
    8.             if (ext == ".obj")
    9.             {
    10.                
    11.                 list.Add(fileName);
    12.             }
    13.            
    14.         }
    15.        
    16.        
    17.         string[] subdirectoryEntries = Directory.GetDirectories(targetDirectory);
    18.         foreach (string subdirectory in subdirectoryEntries)
    19.         {
    20.             ProcessDirectory(subdirectory);
    21.         }
    Any help would be appreciated. Thanks in advance.