Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Formatted output with Debug.Log()

Discussion in 'Scripting' started by boylesg, May 15, 2016.

  1. boylesg

    boylesg

    Joined:
    Feb 18, 2016
    Posts:
    275
    I am not getting any straight answers from google that work.

    How do you do the equivalent of C++ printf("%d", nNum);
     
    Hunterz_Shadow likes this.
  2. lordofduct

    lordofduct

    Joined:
    Oct 3, 2011
    Posts:
    8,380
    For individual values (each type takes its own format possibilities):
    Debug.Log(nNum.ToString(...));

    For multi-parameter strings:
    Debug.Log(string.Format(...));
    https://msdn.microsoft.com/en-us/library/system.string.format(v=vs.110).aspx

    Bookmark the MSDN webpage, refer to it whenever you want, as it contains the documentation of the entire .Net framework, as well as example uses.
     
  3. boylesg

    boylesg

    Joined:
    Feb 18, 2016
    Posts:
    275
    It's a start.

    Any idea where in all that it explains the syntax of the formating....along the lines of what %d means with printf.
     
  4. TheSniperFan

    TheSniperFan

    Joined:
    Jul 18, 2013
    Posts:
    712
    Code (csharp):
    1. Debug.LogFormat("Number: {0}, string {1}, number again: {0}, character: {2}", num, str, chr);
     
  5. lordofduct

    lordofduct

    Joined:
    Oct 3, 2011
    Posts:
    8,380
  6. AdamBebko

    AdamBebko

    Joined:
    Apr 8, 2016
    Posts:
    161
    Just to update this to be more modern:

    int count = 5;
    Debug.Log($"I have {count} cakes");

    this will output "I have 5 cakes"
     
  7. datamachina

    datamachina

    Joined:
    Mar 15, 2022
    Posts:
    1
    int myInt = 10;;
    float myFloat = 2.0f;;
    object[] args = {myFloat, myInt};
    Debug.LogFormat("My float is {0} and my int is {1}", args);
     
  8. AdamBebko

    AdamBebko

    Joined:
    Apr 8, 2016
    Posts:
    161

    Although this works fine, this is not very readable in my opinion. Why might this better than string interpolation?
     
  9. JeffDUnity3D

    JeffDUnity3D

    Unity Technologies

    Joined:
    May 2, 2017
    Posts:
    14,446
    Just personal preference. I typically do

    Debug.Log("Count = " + count.ToString());