Debug.Log
Declaration
public static void Log(object message);public static void Log(object message, Object context);Параметры
| Параметр | Описание |
|---|---|
| сообщение | Строка или объект, который будет преобразован в строку для отображения. |
| контекст | Объект, к которому относится сообщение. |
Описание
Заносит сообщение в журнал в Консоль Unity.
Используйте Debug.Log чтобы выводить информационные сообщения, помогающие отлаживать приложение. Например, можно вывести сообщение с GameObject.name и сведениями о текущем состоянии объекта.
Вы можете форматировать сообщения с помощью сцепления строк:
Debug.Log("Text: " + myText.text);
Вы также можете использовать Rich Text markup.
Если вы передаете GameObject или Component в качестве дополнительного параметра context, Unity временно выделяет этот объект в окне Hierarchy при нажатии кнопки сообщения журнала в Console. Используйте объект context, если у вас много экземпляров объекта в Scene, чтобы вы могли определить, какой из них вызвал сообщение. Example 2ниже иллюстрирует работу этой функции. При запуске этого примера сначала щелкните один из кубов, созданных в Scene. В примере печатается сообщение журнала для Console. Когда вы нажимаете на сообщение, Unity выделяет объект context в окне Hierarchy — в данном случае, куб, на который вы нажали в окне Scene.
Пример 1: Показать некоторые виды использования Debug.Log:
using UnityEngine; using System.Collections;
public class MyGameClass : MonoBehaviour { // A Light used in the Scene and needed by MyGameMethod(). public Light light;
void MyGameMethod() { // Message with a GameObject name. Debug.Log("Hello: " + gameObject.name);
// Message with light type. This is an Object example. Debug.Log(light.type);
// Message using rich text. Debug.Log("<color=red>Error: </color>AssetBundle not found"); } }
Пример 2: Показать выбор нажатого GameObject:
using System.Collections; using System.Collections.Generic; using UnityEngine;
// Debug.Log example // // Create three cubes. Place them around the world origin. // If a cube is clicked use Debug.Log to announce it. Use // Debug.Log with two arguments. Argument two allows the // cube to be automatically selected in the hierarchy when // the console message is clicked. // // Add this script to an empty GameObject.
public class Example : MonoBehaviour { private GameObject[] cubes;
void Awake() { // Create three cubes and place them close to the world space center. cubes = new GameObject[3]; float f = 25.0f; float p = -2.0f; float[] z = new float[] {0.5f, 0.0f, 0.5f};
for (int i = 0; i < 3; i++) { // Position and rotate each cube. cubes[i] = GameObject.CreatePrimitive(PrimitiveType.Cube); cubes[i].name = "Cube" + (i + 1).ToString(); cubes[i].transform.Rotate(0.0f, f, 0.0f); cubes[i].transform.position = new Vector3(p, 0.0f, z[i]); f -= 25.0f; p = p + 2.0f; }
// Position and rotate the camera to view all three cubes. Camera.main.transform.position = new Vector3(3.0f, 1.5f, 3.0f); Camera.main.transform.localEulerAngles = new Vector3(25.0f, -140.0f, 0.0f); }
void Update() { // Process a mouse button click. if (Input.GetMouseButtonDown(0)) { var ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit hit;
if (Physics.Raycast(ray, out hit)) { // Visit each cube and determine if it has been clicked. for (int i = 0; i < 3; i++) { if (hit.collider.gameObject == cubes[i]) { // This cube was clicked. Debug.Log("Hit " + cubes[i].name, cubes[i]); } } } } } }
Примечание: Unity также добавляет сообщения Debug.Log в файлы журнала Редактора и Игрока. Для получения дополнительной информации о доступе к этим файлам на различных платформах, см. Журнальные файлы ссылка.
Дополнительные ресурсы: MonoBehaviour.print.