Overriding the ToString method

The following code sample 2-3 demonstrates the convenience of the ToString method when used in conjunction with the Debug.Log debugging. ToString lets you convert an object to a human-readable string that can be output to Console. In C#, every class inherits the ToString method by default. This means that using inheritance and polymorphism, you can override the ToString method of your class that customizes it as required and produce a more readable and accurate debug string that represents your class members. Consider the following code sample 2-4 that overrides ToString. If you get into the habit of overriding ToString for every class you make, your classes will become easier to debug:

using UnityEngine; using System.Collections; ...

Get Mastering Unity Scripting now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.