Properties
Properties: smart variables. Not only can u retrive info from them, but u can also run functionality through them. In default get and set are authorities of a property(属性的权限).
KEY: How to declare our own properties?
For example, create a game state to check if our game is over. 我们一般都会像下面这样写个bool进行判断。
public class GameManager : MonoBehaviour
{
public bool isGameOver;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
public void GameOver(){
isGameOver = true;
// call the UI manager and enable the game over screen.
}
}
但是现在问题是,我们希望isGameOver
是可读的而不可手动修改的(即可以get但不能set),这时候,我们就要用到properties相关。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameManager : MonoBehaviour
{
private bool isGameOver;
//property
public bool IsGameOver
{
get
{
return isGameOver;
}
set
{
if(value == true){
Debug.Log("the game is over");
}
isGameOver = value;
//keyword value automatically interpret the value that u assigned to it.
// ensure the value u assign is the proper type
}
}
// Start is called before the first frame update
void Start()
{
isGameOver = false;
}
// Update is called once per frame
void Update()
{
if(Input.GetKeyDown(KeyCode.Space)){
IsGameOver = true;
}
}
/*
public void GameOver(){
isGameOver = true;
// call the UI manager and enable the game over screen.
}*/
}
Auto Properties
上一节的property的设定形式,如果你不想要将函数判断放在set里的话,可以直接这样声明property
public bool IsGameOver{get; set;}
如果我们只想当前的脚本可以对这个变量进行修改的话
public bool IsGameOver{get; private set;}
// ALL our obj in our game can read the value, however it won't be able to set it.
同理如果只想它本身和子类对这个变量进行修改,就把private
改为protected
When to use Properties?
- In game manager. (game over? level?
- 由于property不能再u3d的inspector上显示,所以通常都是将一些不需要从控制面板上获取或者修改的变量设置为property