Version: 2022.3

变量和 Inspector


正如其他组件通常具有可在 Inspector 中编辑的属性一样,您也可以让自己脚本中的值可在 Inspector 中编辑。

using UnityEngine;
using System.Collections;

public class MainPlayer : MonoBehaviour 
    public string myName;
    // 此函数用于初始化
    void Start () 
        Debug.Log("I am alive and my name is " + myName);

此代码在 Inspector 中创建一个标记为“My Name”的可编辑字段。

The Inspector might display variable names differently to how you define them in a script if the name conforms to one of a set of rules:

  • Removes “m_” from the beginning
  • Removes “k” from the beginning
  • Removes “_” from the beginning
  • Capitalizes the first letter
  • Adds a space between lowercase and uppercase characters
  • Adds a space between an acronym and an uppercase character at the beginning of the next word

There are some special cases, such as “iPad” or “x64”, where these rules are not applied.

Unity 通过在变量名称中出现大写字母的位置引入空格来创建 Inspector 标签。但是,这纯粹是出于显示目的,在代码中应始终使用变量名称。如果编辑该名称,然后按 Play,您将看到消息中包含您输入的文本。

In C#, the simplest way to see a variable in the Inspector is to declare it as public. An alternative method is to use SerializeField. Conversely, you can use HideInInspector to prevent a public variable from being displayed in the Inspector.

Unity 实际上允许您在游戏运行时更改脚本变量的值。此功能很有用,无需停止和重新启动即可直接查看更改的效果。当游戏运行过程结束时,变量的值将重置为按下 Play 之前所处的任何值。这样可确保自由调整对象的设置,而不必担心会造成任何永久性损坏。