[U3D Learning Note] Unity C# Survival Guide (11) -- Properties

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值