How to dynamically create buttons based on contents of a list using C#?

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class myGUIProblem : MonoBehaviour 
{
	
	public List<Texture> myList;
	
	public List<Texture> _TextureLoader(string _TexturePath)
	{
	
		int myCounter = 0;
		
		List<Texture> myTextureList = new List<Texture>();
		
		while (myCounter < 100)
		{
		
			if (Resources.Load(_TexturePath + myCounter))
			{
		
				myTextureList.Add((Texture)Resources.Load((_TexturePath + myCounter)));
		
				myCounter++;
			
			}
			
			else
			{
				
				break;
			
			}
		
		}
		
		return myTextureList;
		
	}
	
	void OnGUI()
	{
	
		//When this button is pressed, create buttons from list, using textures from that list.
		if (GUI.Button(new Rect(0, 0, 100, 50), "myButton"))
		{
		
			myList = _TextureLoader("Texture/");
			
			Debug.Log(myList.Count);
			
			for (int a = 0; a < myList.Count; a++)
			{
			
				if (GUI.Button(new Rect(0, (50 + (50 * a)), 100, 50), (Texture)myList[a]))
				{
				
					//
					
				}
				
			}
			
			myList.Clear();
			
		}
		
	}
	
}
  • I have a list myList that contains Textures.
  • When I press a button myButton, I want to create new buttons based on the contents of the list.

QUESTION: How do I dynamically create buttons based on the contents of myList? Any help is much appreciated! ~:]

Looks like you’re pretty close. 1. Do not load the textures in OnGUI. If it only needs to happen once, do it in Start. If it may change during game play, detect that event and do it in Update. 2. Use GUILayout as it will make adding/positioning the buttons easier.