What is ToString?
ToString() is a method that all objects have, which converts objects to strings. It's used to convert numbers to strings or express object information as text.
Basic Concepts
- ToString(): Method that converts objects to strings
- Built-in: All classes inherit ToString() from Object
- Override: Can override ToString() to match your class
- Format Specifiers: Can convert numbers to desired formats
Basic Usage
Converting Numbers to Strings
using UnityEngine;
public class BasicToString : MonoBehaviour
{
void Start()
{
int number = 100;
string text = number.ToString();
Debug.Log("Number: " + text);
float pi = 3.14f;
string piText = pi.ToString();
Debug.Log("Pi: " + piText);
bool isTrue = true;
string boolText = isTrue.ToString();
Debug.Log("Boolean: " + boolText);
}
}
Using with String Interpolation
using UnityEngine;
public class StringInterpolation : MonoBehaviour
{
void Start()
{
int score = 1500;
int level = 5;
string message = $"Score: {score.ToString()}, Level: {level.ToString()}";
Debug.Log(message);
string message2 = $"Score: {score}, Level: {level}";
Debug.Log(message2);
}
}
Number Format Specifiers
Integer Format
using UnityEngine;
public class IntegerFormat : MonoBehaviour
{
void Start()
{
int number = 12345;
Debug.Log(number.ToString());
Debug.Log(number.ToString("D"));
Debug.Log(number.ToString("D8"));
Debug.Log(number.ToString("x"));
Debug.Log(number.ToString("X"));
Debug.Log(number.ToString("X8"));
}
}
Float Format
using UnityEngine;
public class FloatFormat : MonoBehaviour
{
void Start()
{
float number = 1234.5678f;
Debug.Log(number.ToString());
Debug.Log(number.ToString("F"));
Debug.Log(number.ToString("F2"));
Debug.Log(number.ToString("F4"));
Debug.Log(number.ToString("E"));
Debug.Log(number.ToString("e"));
Debug.Log(number.ToString("G"));
Debug.Log(number.ToString("N"));
Debug.Log(number.ToString("N2"));
Debug.Log(number.ToString("C"));
Debug.Log(number.ToString("C2"));
}
}
Percent Format
using UnityEngine;
public class PercentFormat : MonoBehaviour
{
void Start()
{
float ratio = 0.75f;
Debug.Log(ratio.ToString("P"));
Debug.Log(ratio.ToString("P0"));
Debug.Log(ratio.ToString("P2"));
}
}
Date/Time Format
DateTime ToString
using System;
using UnityEngine;
public class DateTimeFormat : MonoBehaviour
{
void Start()
{
DateTime now = DateTime.Now;
Debug.Log(now.ToString());
Debug.Log(now.ToString("d"));
Debug.Log(now.ToString("D"));
Debug.Log(now.ToString("t"));
Debug.Log(now.ToString("T"));
Debug.Log(now.ToString("yyyy-MM-dd HH:mm:ss"));
Debug.Log(now.ToString("MM/dd/yyyy"));
}
}
Overriding ToString() in Classes
Default ToString()
using UnityEngine;
public class Player
{
public string name;
public int level;
public int hp;
}
public class ToStringOverride : MonoBehaviour
{
void Start()
{
Player player = new Player();
player.name = "Warrior";
player.level = 10;
player.hp = 100;
Debug.Log(player.ToString());
}
}
Overriding ToString()
using UnityEngine;
public class Player
{
public string name;
public int level;
public int hp;
public override string ToString()
{
return $"Name: {name}, Level: {level}, HP: {hp}";
}
}
public class ToStringOverride : MonoBehaviour
{
void Start()
{
Player player = new Player();
player.name = "Warrior";
player.level = 10;
player.hp = 100;
Debug.Log(player.ToString());
}
}
ToString() in Unity MonoBehaviour
using UnityEngine;
public class Enemy : MonoBehaviour
{
public string enemyName;
public int hp;
public int maxHp;
public override string ToString()
{
return $"{enemyName} (HP: {hp}/{maxHp})";
}
void Start()
{
enemyName = "Goblin";
hp = 50;
maxHp = 50;
Debug.Log(this.ToString());
}
}
Practical Usage Examples
Example 1: Score Display
using UnityEngine;
using UnityEngine.UI;
public class ScoreDisplay : MonoBehaviour
{
public Text scoreText;
private int score = 0;
void Update()
{
scoreText.text = "Score: " + score.ToString();
scoreText.text = $"Score: {score}";
}
void AddScore(int points)
{
score += points;
}
}
Example 2: Time Display
using System;
using UnityEngine;
using UnityEngine.UI;
public class TimeDisplay : MonoBehaviour
{
public Text timeText;
void Update()
{
float time = Time.time;
int minutes = (int)(time / 60);
int seconds = (int)(time % 60);
timeText.text = $"{minutes.ToString("D2")}:{seconds.ToString("D2")}";
}
}
Example 3: Percentage Display
using UnityEngine;
using UnityEngine.UI;
public class HealthBar : MonoBehaviour
{
public Text healthText;
public int currentHp = 75;
public int maxHp = 100;
void Update()
{
float percentage = (float)currentHp / maxHp;
healthText.text = $"Health: {percentage.ToString("P0")} ({currentHp}/{maxHp})";
}
}
Example 4: Currency Display
using UnityEngine;
using UnityEngine.UI;
public class CurrencyDisplay : MonoBehaviour
{
public Text goldText;
private int gold = 1234567;
void Update()
{
goldText.text = "Gold: " + gold.ToString("N0");
goldText.text = gold.ToString("C0");
}
}
Example 5: Debug Information Output
using UnityEngine;
public class DebugInfo : MonoBehaviour
{
public Vector3 position;
public float speed;
public bool isMoving;
public override string ToString()
{
return $"Position: {position}, Speed: {speed.ToString("F2")}, Moving: {isMoving}";
}
void Update()
{
Debug.Log(this.ToString());
}
}
Format Specifier Summary
Number Formats
| Format |
Description |
Example |
D or d |
Decimal |
123.ToString("D") → "123" |
D5 |
Decimal (5 digits) |
123.ToString("D5") → "00123" |
X |
Hexadecimal (uppercase) |
255.ToString("X") → "FF" |
x |
Hexadecimal (lowercase) |
255.ToString("x") → "ff" |
F or f |
Fixed point |
3.14.ToString("F2") → "3.14" |
E or e |
Exponential notation |
1234.ToString("E") → "1.234000E+003" |
N or n |
Number format (thousand separators) |
1234.ToString("N") → "1,234.00" |
C or c |
Currency format |
1234.ToString("C") → "$1,234" |
P or p |
Percent |
0.75.ToString("P") → "75.00 %" |
Date Formats
| Format |
Description |
Example |
d |
Short date |
DateTime.Now.ToString("d") → "1/15/2024" |
D |
Long date |
DateTime.Now.ToString("D") → "Monday, January 15, 2024" |
t |
Short time |
DateTime.Now.ToString("t") → "3:30 PM" |
T |
Long time |
DateTime.Now.ToString("T") → "3:30:45 PM" |
yyyy-MM-dd |
Custom format |
DateTime.Now.ToString("yyyy-MM-dd") → "2024-01-15" |
Notes
- Null Handling: Calling ToString() on null object throws NullReferenceException
- Performance: String interpolation (
$"...") automatically calls ToString(), so it's convenient
- Locale: Currency (C) or date formats may vary depending on system locale
- Override: Overriding ToString() to match your class is useful for debugging
Practical Tips
Tip 1: Using with Null Check
using UnityEngine;
public class NullSafeToString : MonoBehaviour
{
void Start()
{
object obj = null;
string result = obj?.ToString() ?? "null";
Debug.Log(result);
if (obj != null)
{
Debug.Log(obj.ToString());
}
}
}
Tip 2: Combining Multiple Values
using UnityEngine;
public class CombineValues : MonoBehaviour
{
void Start()
{
int score = 1500;
int level = 5;
float time = 123.45f;
string info = $"Score: {score.ToString("N0")}, Level: {level}, Time: {time.ToString("F2")}s";
Debug.Log(info);
}
}
Tip 3: Conditional Format
using UnityEngine;
public class ConditionalFormat : MonoBehaviour
{
void Start()
{
float number = 1234.567f;
string formatted = number % 1 == 0
? number.ToString("N0")
: number.ToString("F2");
Debug.Log(formatted);
}
}
Tip 4: Outputting List Elements
using System.Collections.Generic;
using UnityEngine;
public class ListToString : MonoBehaviour
{
void Start()
{
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
string result = string.Join(", ", numbers.ConvertAll(x => x.ToString()));
Debug.Log(result);
}
}
← Back to Table of Contents