- Home /
Chat Window - BeginScrollView - AutoScroll
I was hoping to use GUILayout and ScrollView.
I want to create a chat window that autoscrolls the new messages, but I am not sure how to do this. I don't want to show any scrollbars either.
I was hoping that I could get away with some relatively simple code w/out calculating every position for every single line of text.
Is there an example of this?
Any hints?
THanks,
stringa
I figured it out. If you just set the Scroll Position to something rediculously high, it will always be scroll to the bottom of the scrollView. Also, I set the GUIStyle to none, and walla...I have what I was looking for.
At least I don't have to Calculate the size of every box and what the real scroll position would be.
Answer by Bampf · Oct 19, 2010 at 03:29 AM
Presumably each line of text is the same height, so all you need to know for each line's position is the line #. Multiply it by the line height; the top line will be at position 0 (typically.)
If you have an array of lines, the last position would be (array-length - 1) * lineHeight. (Make sure you handle the case where the array is empty though.)
If you use GUI.* for each line, you can set the Rect of each line yourself. Define lineWidth and lineHeight as public variables that you set in the inspector. Then loop over each line you want to display:
- First rect: (0, 0 * lineHeight, lineWidth, lineHeight)
- Second rect: (0, 1 * lineHeight, lineWidth, lineHeight)
- Third rect: (0, 2 * lineHeight, lineWidth, lineHeight)
- etc.
Set the scroll-view's position to the last line, and you're done. It gets a little trickier if you want to wrap each line of text, obviously. (see next paragraph for ideas)
If you were planning to use GUILayout. instead of GUI., you can do pretty much the same thing but you will either need to calculate each line's height ahead of time (using GUIStyle.CalcHeight), OR, use GUILayoutUtility.GetLastRect to find out how tall each line was after the fact. GetLastRect can be a little tricky, make sure you read up on it if you decide to go that way.
Ha! I like your solution, it's very direct! But perhaps the methods I describe will help someone else some day, someone who needs to scroll to a particular line, for instance.
Thanks for the info though. I don't really think about GUIUtility class for some reason....
Did you know that you can post (and accept) your own answer? I won't be offended if you do that- you came up with your own solution in the end.
Answer by Mervill · May 23, 2013 at 12:04 AM
You want:
public Vector3 scrollPosition;
void OnGUI(){
scrollPosition = GUILayout.BeginScrollView([...])
{...}
GUILayout.EndScrollView();
}
void SomeEvent(){
// Force the scrollbar to the bottom position.
scrollPosition.y = Mathf.Infinity;
}