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

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;
}

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.