【问题标题】:Initialize a variable and print its value on every frame初始化一个变量并在每一帧上打印它的值
【发布时间】:2019-01-28 14:54:43
【问题描述】:

我正在尝试为对象实现“健康”属性。我希望在游戏开始时生命值等于 100,并在每一帧打印生命值以便调试。

这是我的代码:

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

public class healthScript : MonoBehaviour {

    // Use this for initialization
    void Start () {

        public int health = 0;
    }

    // Update is called once per frame
    void Update () {

    }
}

我该怎么做?

【问题讨论】:

  • 这段代码并没有真正做任何事情。目前还不清楚你在问什么。如果应该将属性初始化为 100,请在一些初始化代码中执行此操作。如果你想记录值,有一个记录器:docs.unity3d.com/ScriptReference/Logger.html

标签: c# unity3d


【解决方案1】:

如果你想调试每一帧的值,这将起作用:

public class healthScript : MonoBehaviour
{
   //Variable declaration
   private int _health;

   // Use this for initialization
   void Start()
   {
        _health = 100;
   }

    // Update is called once per frame
    void Update () {
        Debug.Log(_health);
    }
}

您的错误是您在 Start 方法中定义了变量,因此它仅在此方法中可见。但是,当您在类内部但在任何方法之外定义变量时,它在所有类中都是可见的。但是对于在类内部和外部可见的变量,它们的声明位置请参见manual 关于访问修饰符。

但我可以建议你一个更方便的方法:

public class healthScript : MonoBehaviour
{
    //Property
    public int Health
    {
        get { return _health; }
        set
        {
            _health = value;
            Debug.Log("Health changed to value: " + _health);
        }
    }

    //Variable declaration
    private int _health = 100;
}

在这种情况下,您使用属性来调试您的健康值。因此,每次您将像 Health = someIntValue 这样更改健康值时,您都会收到有关您当前健康水平的控制台消息。

【讨论】:

    猜你喜欢
    • 2017-01-04
    • 1970-01-01
    • 2021-09-29
    • 1970-01-01
    • 2022-06-11
    • 2016-11-25
    • 2017-05-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多