官术网_书友最值得收藏!

Time for action – making a variable private

Not all variables need to be public. If there's no need for a variable to be changed in the Inspector panel nor be accessed from other scripts, it doesn't make sense to clutter the Inspector panel with needless properties. In LearningScript, perform the following steps:

  1. Change line 6 to the following:
    private int number1 = 2;
  2. Change line 7 to the following:
    int number2 = 9;
  3. Save the file.
  4. In Unity, select Main Camera.

What just happened?

You will notice in the Inspector panel that both properties, Number 1 and Number 2 are gone.

  • Line 6: private int number1 = 2;

    The preceding line explicitly states that the number1 variable is to be private, therefore the variable is no longer a property in the Inspector panel. It is now a private variable to store data.

  • Line 7: int number2 = 9;

    The number2 variable is no longer visible as a property either, but you didn't specify it as private.

If you don't explicitly state whether a variable will be public or private, by default, the variable will implicitly be private.

Tip

It is good coding practice to explicitly state whether a variable will be public or private.

So now when you click on Play, the script works exactly as it did before. You just can't manipulate the values manually in the Inspector panel anymore.

主站蜘蛛池模板: 白沙| 法库县| 江永县| 白水县| 涞水县| 玛沁县| 大冶市| 霍邱县| 天全县| 桂阳县| 青神县| 甘南县| 昭通市| 乌兰浩特市| 东港市| 丹凤县| 松阳县| 麻江县| 沧州市| 蕲春县| 和静县| 大同县| 云霄县| 金塔县| 洞头县| 双牌县| 平舆县| 昆明市| 通海县| 那曲县| 津南区| 永嘉县| 二连浩特市| 铅山县| 怀远县| 淅川县| 酒泉市| 梁河县| 中阳县| 南靖县| 瑞昌市|