变量作用域
代码块通常用于定义变量作用域。
用 { } 表示。
using System.Collections;using System.Collections.Generic;using UnityEngine;public class L06 : MonoBehaviour{public int alpha; //在L06类的作用域内private int beta = 0; //在L06类的作用域内private int gamma = 5; //在L06类的作用域内void Example(int pens,int crayons){int answer;answer = pens * crayons * alpha;Debug.Log(answer);}void Update(){Debug.Log("Alpha is set to:" + alpha);}}
访问修饰符
类内定义的变量不同于函数内声明的变量,前者分配有访问修饰符。
访问修饰符是在声明变量时放在数据类型前的关键词。用途是能够看到变量或函数的位置。
一般而言,如果其他脚本需要访问某个变量或函数,就需要将其公开,否则就应该设为私有。
设为公开意味着可以从类外部访问这个变量。也意味着这个变量可在Inspector中的组件上显示和编辑。
未指定类型的默认为私有 private,通常将所有属于类而非函数的变量都设为私有。
