Hello!
In this tutorial we will cover the basics of creating a Scroll Rect that resizes itself according to the content. Let's get started. You can play with the button and make him look good, but the focus of this tutorial is to create the Scroll Rect functionality itself.
5) Creating the Scroll Bar
After all these steps. Drag and Drop the button prefab and parent it to the Grid Panel.
If you duplicate the button enough and hit play, you will notice that the Grid Will resize itself and the Scroll Rect will keep it in its bounds when you drag the content. Now as you have noticed, there is a problem with this aproach. The Scroll Rect doest not put the content on the begining. To solve that issue we will create a script. 6) Finishing touches
using UnityEngine; using UnityEngine.UI; using System.Collections; public class CreateButton : MonoBehaviour { // Button prefab // Drag and Drop into inspector public GameObject prefab; // Grid layoutgroup // Drag and Drop into inspector public Transform target; // ScrollRect for repositioning purposes // Drag and Drop into inspector public ScrollRect scroll; // For Debugging purpose the function that creates the buttons is triggered when you press "P" private void Update() { if(Input.GetKeyDown(KeyCode.P)) { Create(); } } // Create the object and assign the Grid as his parent. public void Create() { GameObject temp = GameObject.Instantiate(prefab, Vector3.zero,Quaternion.identity) as GameObject; temp.transform.SetParent(target); StartCoroutine(Reposition()); } // After you instantiate the object, there is a slight delay. // So if you attempt to reposition the objects within the ScrollRect after that it will not work. public IEnumerator Reposition() { yield return new WaitForSeconds(0.05f); // Reposition the content on the beginning scroll.horizontalNormalizedPosition = 0f; // if your scroller is meant to go up and down // use: scroll.verticalNormalizedPosition = 0f; } } After this, simply drag and drop the script onto a Game Object on the scene and assign the variables in the inspector. Hit play and see the result. If your have any question about this tutorial leave a comment in the section bellow. Thank you for reading. PS: The source is available for download:
2 Comments
|