I’ve only been using unity for about a week so sorry for the n00b question, I have a Scene that’s supposed to act as a score screen and display all the score data for different players in the game, I have a Scroll view with a vertical layout group on the content, I have a text file with t he data separated by lines, and I have a stream reader to pull from the text file, but I can’t seem to get it to load into the scroll view properly,I just started using Unity about a week ago so sorry for the n00b question,
So I have a Scene to view score data, I added a scroll view with a vertical layout group as a child, have a text file with each entry separated on a new line, have a stream reader set up to read the text file, but haven’t been able to get the scores loaded into the scroll view properly.
One thing to realize is that the scrollview can hold anything. Not just text. That makes it powerful but also means you need to work a little to get it to work the way you want it to.
If your scrollview is set up in unity, make sure to add the following components: Layout → Vertical Layout Group and Layout → Content size fitter. The vertical layout group will child anything under it and place it nicely in the box while the content size fitter helps make the size of the children appropriate (you’ll probably find that in the second one, you need to set "child force expand horizontal and child control size vertical, but experiment.)
Save a reference to the scrollview. You’ll need it later:
RectTransform SomeScrollRect = GameObject.Find(" ").GetComponent<ScrollRect>();
In quotes, you’ll use the name that you give the object in the inspector. Make it unique.
Then when you want to generate a text option in code, do this:
DefaultControls.Resources TempResource = new DefaultControls.Resources();
GameObject NewText = DefaultControls.CreateText(TempResource);
(You could also use CreateButton if you want the list to be interactive.)
Finally, you’ll need to add a LayoutElement to your object:
NewText.AddComponent<LayoutElement>();
Finally, add the new text to the scrollview:
Edit: You need to parent the content box, not the ScrollView, I wrote a function for this that I use myself. Sorry I put the wrong parent here: I call my function FindContent because it returns a reference to the content box of the scrollview. /Edit
public RectTransform FindContent (GameObject ScrollViewObject) {
RectTransform RetVal = null;
Transform[] Temp = ScrollViewObject.GetComponentsInChildren<Transform>();
foreach (Transform Child in Temp) {
if (Child.name == "Content") { RetVal = Child.gameObject.GetComponent<RectTransform>(); }
}
return RetVal;
}
Then you can set the parent like this:
NewText.transform.SetParent(FindContent(SomeScrollRect));