[Help!] Chat Scrollview from Bottom to Top - Scripting

Hey guys… I am new to the Unity Forum Community, but I need some “basic” help with my script:
I found this script (down below) from the Unity Asset Store (called Unity Multiplayer Chat). The whole code works and is fully functional - however some of the features I want to change.

I changed the code so that now whenever you talk, your message goes below the previous messages, kind of like Minecraft’s chat box. However, whenever I talk, the scrollbar won’t auto - scroll down to show the message you just wrote, or a message that another player wrote. It just stays at the very top of the scrollbar, forcing you to scroll down manually to see the most-recent message.

I’d hopefully like to change that so it will auto-scroll down to the most recent message posted, making it exactly like a Minecraft chat box. In the picture below, you can tell by the scroll bar that there are more messages below. However, the scrollbar doesn’t automatically scroll to them - you have to do it yourself.

Picture:
2169797--143579--Screen Shot 2015-06-21 at 8.51.48 PM.png

This is the code that I need to edit - it contains the scrollbar stuff:

scrollPos = GUILayout.BeginScrollView(scrollPos); //Scroll View begins... it's position is scrollPos
GUILayout.FlexibleSpace(); 
for (inti = 0; i < messages.Count; i++) 
 {
GUILayout.BeginHorizontal("Box");
if (messages[i].name == User)
 {
GUI.color = newColor(My_Color.r, My_Color.g, My_Color.b, m_alpha);
 }
else
 {
GUI.color = newColor(messages[i].color.r, messages[i].color.g, messages[i].color.b, m_alpha);

 }
GUILayout.Label(""+messages[i].name+""); 
GUILayout.Space(5);
GUI.color = newColor(1, 1, 1, m_alpha);
GUILayout.Label(messages[i].text);
GUILayout.EndHorizontal();
 } 
GUILayout.EndScrollView();                                        //Scroll View ends here

To fix this I think you may need to make the scrollPos at the end of the Scroll View to make it start at the bottom… however I’m really not sure how to do it - I only started Unity about 1 month ago. Just ignore most of the color stuff, since that is for the chat color.

Thanks for all your help, guys <3 :smile:

Google is your friend ScrollView - How to set the scroll position programatically? - Unity Engine - Unity Discussions

Thanks… Though I don’t really understand the code - I’m pretty new to all the UI stuff.

Good luck with your “Immortal Thought” game :slight_smile: Tell me when it’s done so I can play it

One Advice you currently use the old gui, there is a new ui which makes things easier. Redirecting to latest version of com.unity.ugui

You mean the drag-and drop one in the Inspector? Yeah, I did that for my Main Menu Scene. But doing it manually for a chat box seemed harder… so I just found some code from the Asset Store that worked :wink:

Is there a way to make all the chat messages formatted to the left side, next to the name, instead of centered in the middle (look at the chat message picture above). Like this:

EXBOW: HEY
EXBOW: WHAT’S UP

Instead of:

EXBOW: ______HEY (I used the ____ the space it out)
EXBOW: ___WHAT’S UP

Here’s the whole entire code… most of it doesn’t matter - I just need to know where the part is that makes the text centered, and then how to fix that to make it formatted to the left side… THANKS FOR HELPING:

////////////////////////////////CODEWRITTEBYBRINERLOVOGAMES2014/////////////////////
//////////UMCCHATSYSTEM////////////////////////////////////////////////////////////////
///////////////INASCENEWITHASERVERREADY////////////////////////////////////////////
///////////PUTTHISSCRIPTANDAGOWITHANETWORKVIEW///////////////////////////////////
/////////////////////////////////ANDREADYTOCHAT//////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////
usingUnityEngine;
usingSystem.Collections;
usingSystem.Collections.Generic;

[RequireComponent(typeof(NetworkView))]
[RequireComponent(typeof(AudioSource))]
publicclassbl_MultiplayerChat : MonoBehaviour {


publicstructChatData
{
publicstringname { get; set; } //Nameofsender
publicstringtext { get; set; } //Messagetext
publicColorcolor { get; set; } //Sendercolor
publicfloattimer { get; set; } //Removemessageaftercertaintime

publicChatData(stringstring1, stringstring2, Colorcolor1, floattimer1)
{
name = string1;
text = string2;
color = color1;
timer = timer1;
}

}

publicNetworkViewnet;
///<summary>
///ListwithalMessagesinRoom
///</summary>
publicList<ChatData> messages = newList<ChatData>();
publicstringplist;
publicstringgameversion = "Version: 3.5.1 Beta";
///<summary>
///SkinforGUIs
///</summary>
publicGUISkinm_Skin = null;
///<summary>
///Colorforplayernamedysplay
///</summary>
publicAudioClipSend_Sound;
publicAudioSourceaudioS;

publicColorMy_Color;
publicColorm_Color;
publicstaticColorSender_Color;
///<summary>
///GetcurrentChatinRoom
///</summary>
publicstaticbl_MultiplayerChatchat;
///<summary>
///ChatGUIHeight
///</summary>
publicintm_Height = 140;
///<summary>
///ScrollforChatlist
///</summary>
privateVector2scrollPos = Vector2.zero;
///<summary>
///Widhtofchatgui
///</summary>
publicintm_Widht = 250;
///<summary>
///Maxwordforsendinchat
///</summary>
publicintm_Max_Lengh = 15;
///<summary>
///StringforSendnewMessage
///</summary>
privatestringchatInput = "";
///<summary>
///its "Apply_alpha" enabledapplythistimeforguichatfade
///</summary>
publicfloatm_Time_To_Fade = 7;
privatefloatm_alpha = 5;
///<summary>
///Timeforremoveoldmessages
///</summary>
publicfloatm_Remove_Time = 20;
staticfloatRemove_Time ;

///<summary>
///itsfalse = guinotfade.
///</summary>
publicboolApply_alpha = true;
///<summary>
///itsfalse = oldmessagesnotremovefromchat
///</summary>
publicboolRemove_OnTime = true;
privatefloatlastUnfocusTime = 0;
///<summary>
///PlayerName + Backup
///</summary>
privatestringUser;
privatestringUserBackUp;
///<summary>
///filtertoavoidunwantedword
///createnewstringtofilteradding: ,"word_to_filter" (allinlowercase).
///</summary>
privatestring[] blacklist = newstring[] {
//"wrong", "test","nopermit","<",
"fuck","damn","shit","hell","bitch","nigga"   //Blacklisted words! Program purpose sonly... No bad intentions! Sorry!
};
privateboolm_isEnabled = true;



///<summary>
///GetPlayerName, SendinaPlayerPrefsinotherSceneforexampleaLobby
///</summary>
voidStart()
{
audioS = GetComponent<AudioSource> ();
net = GetComponent<NetworkView> ();
if(PlayerPrefs.HasKey("UserName")){
User = PlayerPrefs.GetString("UserName");
UserBackUp = User;

}else{
User = "Player"+Random.Range(0,999);
UserBackUp = User;
}
Sender_Color = m_Color;
Remove_Time = m_Remove_Time;
}

voidAwake()
{
chat = this;
}

voidUpdate()
{




if (Remove_OnTime)
{
//Removechatmessageaftertimerreach0
for (inti = 0; i < messages.Count; i++)
{
ChatDataMInfo = messages[i];
MInfo.timer -= Time.deltaTime;
if (MInfo.timer > 0)
{
messages[i] = newChatData(MInfo.name, MInfo.text, MInfo.color, MInfo.timer);
}
else
{
messages.RemoveAt(i);
}
}
}
if (!Apply_alpha || !Network.isClient && !Network.isServer)
return;

if (m_alpha > 0.0f)
{
m_alpha -= Time.deltaTime;
}
if (m_isEnabled)
m_alpha = m_Time_To_Fade;
}

voidOnGUI()
{
if (!Network.isClient && !Network.isServer)
return;

GUI.skin = m_Skin;
GUI.color = newColor(1, 1, 1, m_alpha);
GUI.SetNextControlName("");
//usethisforstaticchat
GUILayout.BeginArea(newRect(0, Screen.height - m_Height, m_Widht+ 30, m_Height),"Chat Room");
GUILayout.BeginHorizontal();
GUILayout.BeginVertical("window");
scrollPos = GUILayout.BeginScrollView(scrollPos);
GUILayout.FlexibleSpace();
for (inti = messages.Count - 1; i >= 0; i--) //Thismakesthemessagestypedgofrom
//for (inti = 0; i < messages.Count; i++)
{
GUILayout.BeginHorizontal("Box");
if (messages[i].name == User)
{
GUI.color = newColor(My_Color.r, My_Color.g, My_Color.b, m_alpha);
}
else
{
GUI.color = newColor(messages[i].color.r, messages[i].color.g, messages[i].color.b, m_alpha);

}
GUILayout.Label(""+messages[i].name+"");
GUILayout.Space(5);
GUI.color = newColor(1, 1, 1, m_alpha);
GUILayout.Label(messages[i].text);
GUILayout.EndHorizontal();
}
GUILayout.EndScrollView();
GUILayout.EndVertical();
GUI.color = newColor(1, 0, 0, m_alpha);
if (GUILayout.Button("X",GUILayout.Width(30),GUILayout.Height(m_Height-35)))
{
m_alpha = 0;
m_isEnabled = false;
GUI.FocusControl("");
GUI.UnfocusWindow();
}
GUILayout.EndHorizontal();
GUI.color = newColor(1, 1, 1, m_alpha);
GUILayout.BeginHorizontal("Box");

if (m_isEnabled)
{
GUI.color = Color.white;
GUI.SetNextControlName("ChatField");
chatInput = GUILayout.TextField(chatInput, m_Max_Lengh, GUILayout.MinWidth(225));
if (GUILayout.Button("SEND", GUILayout.Height(25), GUILayout.Width(69)))
{
SendChat(RPCMode.All);
}
if (GUILayout.Button("CLOSET", GUILayout.Height(25), GUILayout.Width(69)))
{
m_isEnabled = false;
}
if (Apply_alpha)
{
GUI.color = Color.green;
}
else
{
GUI.color = Color.red;
}
if (GUILayout.Button("FADE", GUILayout.Height(25), GUILayout.Width(69)))
{
Apply_alpha = !Apply_alpha;
}


}
else
{
GUI.SetNextControlName("");
}

if (Event.current.type == EventType.keyDown && Event.current.character == '\n' && m_isEnabled)
{

if (GUI.GetNameOfFocusedControl() == "ChatField")
{
if (chatInput.Length > 0)
{
SendChat(RPCMode.All);
//lastUnfocusTime = Time.time;
GUI.FocusControl("ChatField");
}
else
{
m_isEnabled = false;
GUI.SetNextControlName("");
GUI.FocusControl("");
GUI.UnfocusWindow();
}
}
else
{
if (lastUnfocusTime < Time.time - 0.1f)
{
GUI.FocusControl("ChatField");
}
}
}
elseif (Event.current.type == EventType.keyDown && Event.current.character == '\n' && !m_isEnabled)
{
m_isEnabled = true;
GUI.FocusControl("ChatField");
}

GUILayout.FlexibleSpace();
GUILayout.EndHorizontal();
GUILayout.EndArea();
}

voidOnJoinedRoom(){
chatInput = User + " joined the game!";
SendChatServer(RPCMode.All);
}

voidOnPhotonPlayerDisconnected(){
chatInput = User + " left the game!";
SendChatServer(RPCMode.All);
}


voidPlayerlist(stringlist)
{
plist = list;
}



///<summary>
///Sendanewmessagetoserverforallplayer
///</summary>
///<paramname="text">textforshowinchat</param>
publicstaticvoidAddMessage(stringtext,stringsender)
{
Colorcolor = newColor();
color = Sender_Color;
chat.messages.Add( newChatData( sender, text,color,Remove_Time));
if (chat.messages.Count > 15)
chat.messages.RemoveAt(0);
}


[RPC]
voidSendChatMessage(stringtext,stringname)
{
m_alpha = m_Time_To_Fade;
AddMessage(text,name);
if (Send_Sound != null)
{
audioS.clip = Send_Sound;
audioS.Play();
}
}

///<summary>
///GetandSendanewmessageandapplyfilterstringforwronglabels
///</summary>
///<paramname="target"> Networkingtargets</param>
voidSendChat( RPCModetarget)
{
if (chatInput != "" && chatInput != "/p" && chatInput != "/players" && chatInput != "/playerlist" && chatInput != "/plist" && chatInput != "/list" && chatInput != "/P" && chatInput != "/PLAYERS" && chatInput != "/PLAYERLIST" && chatInput != "/PLIST" && chatInput != "/LIST" && chatInput != "/v" && chatInput != "/V" && chatInput != "/version" && chatInput != "/VERSION" && chatInput != "/QUIT" && chatInput != "/quit" && chatInput != "/love" && chatInput != "/LOVE" && chatInput != "/devs" && chatInput != "/DEVS" && chatInput != "/lobby" && chatInput != "/LOBBY")
{

foreach (stringfilterinthis.blacklist)
{
if (chatInput.ToLower().IndexOf(filter) != -1)
{
chatInput = chatInput.ToLower().Replace(filter, "****");
}
}

GetComponent<NetworkView>().RPC("SendChatMessage", target, chatInput,User);
chatInput = "";
}

//In-Game Chat Commands:

if ((chatInput == "/P" || chatInput == "/PLAYERS" || chatInput == "/PLAYERLIST" || chatInput == "/PLIST" || chatInput == "/LIST" || chatInput == "/p" || chatInput == "/players" || chatInput == "/playerlist" || chatInput == "/plist" || chatInput == "/list") && chatInput != "/v" && chatInput != "/V" && chatInput != "/version" && chatInput != "/VERSION" && chatInput != "/QUIT" && chatInput != "/quit" && chatInput != "/love" && chatInput != "/LOVE" && chatInput != "/devs" && chatInput != "/DEVS" && chatInput != "/lobby" && chatInput != "/LOBBY")
{
AddMessage(plist,"[ PlayerList ]");
chatInput = "";
}

if ((chatInput == "/v" || chatInput == "/V" || chatInput == "/version" || chatInput == "/VERSION") && chatInput != "/QUIT" && chatInput != "/quit" && chatInput != "/love" && chatInput != "/LOVE" && chatInput != "/devs" && chatInput != "/DEVS" && chatInput != "/lobby" && chatInput != "/LOBBY") {
AddMessage(gameversion,"[ Server ]");
chatInput = "";
}

if ((chatInput == "/QUIT" || chatInput == "/quit") && chatInput != "/love" && chatInput != "/LOVE" && chatInput != "/devs" && chatInput != "/DEVS" && chatInput != "/lobby" && chatInput != "/LOBBY") {
AddMessage("Bye bye!","[ Server ]");
chatInput = "";
Application.Quit();

}

if ((chatInput == "/love" || chatInput == "/LOVE") && chatInput != "/devs" && chatInput != "/DEVS" && chatInput != "/lobby" && chatInput != "/LOBBY") {
AddMessage("We love you too <3","[ Server ]");
chatInput = "";
}

if ((chatInput == "/devs" || chatInput == "/DEVS") && chatInput != "/lobby" && chatInput != "/LOBBY") {
AddMessage("Creator: Exbow","[ Server ]");
chatInput = "";
}

if (chatInput == "/lobby" | chatInput == "/LOBBY") {
AddMessage("Connecting back to lobby...","[ Server ]");
chatInput = "";
Application.Quit ();
}

}




voidSendChatServer ( RPCModetarget)
{
if (chatInput != "")
{

foreach (stringfilterinthis.blacklist)
{
if (chatInput.ToLower().IndexOf(filter) != -1)
{
chatInput = chatInput.ToLower().Replace(filter, "****");
}
}
User = "[ Server ]";
GetComponent<NetworkView>().RPC("SendChatMessage", target, chatInput,User);
chatInput = "";
User = UserBackUp;
}
}

}

take a look at GUIStyle Unity - Manual: GUI Style (IMGUI System)

I do have a GUISkin for the script - does that mean I have to change the GUISkin to change the formatting?

yes change the parameter alignment

Yikes… would i have to Photoshop it to change the GUISkin, or can I open it in Unity? Sorry I’m really nooby at this stuff…

In the manual everything is described. You have to add a variable from type GUIStyle to your script wich will be your Style for the Label element. Then you can edit your Instance of GUIStyle in the editor.

public ShowLabelScript : MonoBehaviour
{
    public GUIStyle myGUIStyle;

    void OnGUI(){
       GUILayout.Label("TEST", myGUIStyle);
     }
}