Beginners question about outputting the variables in a class to the console

Hi there,

I’m learning about classes and constructors in Unity and I’m wondering how to go about outputting the details within a class to the console?

I’ve written two scripts. One is called Books.cs that has two constructors in it(one empty and the other has arguments passed through it) and the other is called Player.cs which is attached to a game object.

The code in Books.cs is as follows:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Books
{
   public int id;
   public string title;
   public string author;


    public Books(){

    }


   public Books(int id, string title, string author){

       this.id = id;
       this.title = title;
       this.author = author;
   }

}

The Player.cs code is as follows:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Player : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
       
       
        Books books_1 = new Books();
        Books books_2 = new Books(1,"Goosebumps","R.L Stine");

        Debug.Log(books_1);
        Debug.Log(books_2);

      
      
    }

   
}

As you can see I’ve tried to Debug.Log the two instances I’ve created in the Player class but the consoles just outputs “Books” twice.

Do I have to use an array or something to output what shown in the second books_2 variable or something?

Computers are dumb. They dont have any knowledge about what you want to do, unless you tell them exactly what that is. How would the computer know what output you expect, if you write Debug.Log(books_1)? Thats an object, or rather a reference to an object. The computer by itself has no idea what to output you, so you usually get either a default value, or the memory address or something similar outputted, depending on the language.

Inside your Book class, define a method ToString(). Inside that method, return a string that you think represents your book class accurately. For example, "The book " + title + " by " + author + " has the ID: " + id;
You define what is important to output here, as some things may only be used internally!
Now instead of writing Debug.Log(books_2), write Debug.Log(books_2.ToString()), and the computer knows exactly what you want it to do :slight_smile:

2 Likes

Yep, Books is the class, so it’s just reporting the class type. To dig into the properties, use dot notation:
Debug.Log(books_2.title);

2 Likes