Reading the credits from a text file

Don’t worry- this will be an easy tutorial.

 

First off, obviously you have to create the text file.  If it’s large (like mine, if you use a lot of open game art), you might want to mark up every 4 or 5 lines with a special character.  I use a ‘*’.

Here’s an example of what the text file looks like (using Yure Goes Hop Hop as an example).  Note how I mark up the *.

clipboard01

 

1. Adding the text file

It really doesn’t matter where you save it, as long as it’s inside the asset folder.  I personally just save it directly in the asset folder, and call it credits.txt

2. Accessing it via script

2a. Basics

So, Unity has this class called an TextAsset.  Any file can be accessed as a string from the assets folder. Contents are stored as a string in the “text” variable.

Set the TextAsset as a public variable on a custom script (or private with the [SerializeField] tag).  Then set it to credits.txt in the inspector

2b. Creating the array list

I personally use a coroutine to display the credits.  I would suggest polishing this with animation, but for this example I’m going to be simple.  Now, bear in mind, you should only split the text file once.  I usually do it in the coroutine before the infinite loop.

string[] lines = creditsFile.text.Split('*');

2c. Iterating the array list

A for loop is the easiest way to do it, but you want the user to be able to see it in an infinite loop, so…
Well, here’s the whole Coroutine I used in Yure Goes Hop Hop.

IEnumerator Routine()
{
  string[] lines = creditsFile.text.Split('*');
  int i = 0;
  while(gameObject.activeSelf)
  {
    mainInfoText.text = lines[i];
    yield return new WaitForSeconds(5f);
    i++;
    if (i >= lines.Length)
    i = 0;
  }
}

In this script, creditsFile is the Text Asset.  mainInfoText is the text object (or rather, TextMeshPro UI object).  Every 5 seconds, it moves to the next section.

 

Conclusion

Once you have the code working, you can update the text file as you go and not have to make any more code.  It’s still a good idea to test it to make sure the text fits in the text box and doesn’t overflow.

But TextAssets are the easiest way to go in writing credits as you go.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s