Hi guys I'm totally new to Unity3D. I'm trying to create a scrollable button list where users can scroll through a list of buttons inside a panel. So I have a OnGUI function and inside of it I created some buttons that are of the same width and height. Their Y-axis position is separated by about 55 units each. This is all done in Unity's C# script. I attached the script to a panel and that panel is also attached with a vertical scrollbar. I added the Mask component in the panel where I unchecked the Show Mask Graphic. But when I click play, the buttons do not show up at all. Is it possible to create a scrollbar inside the script and attach to the button list? Thanks
3 Answers
Ok I would highly advise you use the new Unity UI system instead of using Immediate Mode GUI (OnGui functions). You can still control things programatically with ease but it is much easier with a canvas to work with.
You mention using panels and masks but they don't mix with the OnGui setup, that is the legacy UI system and should only be used for Unity editor plug ins.
That said there are great learning resources which cover exactly what you need in these three tutorials on the Unity site:
And if you have not got any experience using the newer system the main tutorial page is here.
I hope that helps.
Comments
Try this code:
(taken from the Unity Script Reference for GUI.BeginScrollView)
using UnityEngine;
using System.Collections;
public class ExampleClass : MonoBehaviour {
public Vector2 scrollPosition = Vector2.zero;
void OnGUI() {
scrollPosition = GUI.BeginScrollView(new Rect(10, 300, 100, 100), scrollPosition, new Rect(0, 0, 220, 200));
GUI.Button(new Rect(0, 0, 100, 20), "Top-left");
GUI.Button(new Rect(120, 0, 100, 20), "Top-right");
GUI.Button(new Rect(0, 180, 100, 20), "Bottom-left");
GUI.Button(new Rect(120, 180, 100, 20), "Bottom-right");
GUI.EndScrollView();
}
}
4 Comments
If its in game, I don't recommend OnGUI, rather use the Unity UI components. There is good video on how to create scrolalble lists here: https://www.youtube.com/watch?v=lUun2xW6FJ4
You can add buttons to the vertical or horizontal group easily from editor or from code. You just instantiate button prefabs and place them inside the horizontal group parent.
GameObject horLayoutGroup;
GameObject buttonPrefab;
var myButton = Instantiate(buttonPrefab, new Vector3(default), Quaternion.identity);
myButton.transform.SetParent(horLayoutGroup.transform)
this will automatically scale the entire layout group and place everything neatly next to each other, without having to play with pixel offset.
If you want to add a function to a button, you use the following code:
myButton = GetComponent<Button>();
myButton.onClick.RemoveAllListeners();
myButton.onClick.AddListener(() => SomeClassInstance.PublicFunction);
myButton.onClick.AddListener(() => SomeOtherClassInstance.AnotherPublicFunction);
OnGUIand Mask Component. This will not work. It's hard to tell exactly what you are doing without your code.