[Unity] C#中级编程 - 01 - 可读可写属性

[Unity中文课堂教程] C#中级编程 - 01 - 可读可写属性

原教程视频地址:

《[Unity中文课堂教程预告片] C#中级编程_哔哩哔哩_bilibili

C#中级编程 - Unity中文课堂 (u3d.cn)

内容短小精悍简练,每节只有几分钟。很适合用来预习和复习。

主要代码内容

  • 当外部需要访问类的私有变量时,一般不会直接将私有变量改为公开变量,而是采用另一个公开变量间接访问。

脚本①如下:(被访问)

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Exercise_4_0 : MonoBehaviour
{
	private int him_0 = 0;
	
	public int Him_0		// 命名习惯,第一个字母大写,与原变量第一个字母小写相对应。
	{
		get
		{
			return him_0;
		}
		set 
		{
			him_0 = value;	// 关键字 "value" 代表赋值输入的参数。不要写错成 Him_0
		}
	}
}

脚本②如下:(要访问)

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Exercise_4_1 : MonoBehaviour
{
    void Start()
    {
        // Exercise_4_0 him = new Exercise_4_0(); 	// 脚本①没有继承父类 MonoBehaviour 采用
		Exercise_4_0 him = gameObject.AddComponent<Exercise_4_0>(); // 反之,有继承时采用
		
		him.Him_0 = 5;
        
		Debug.Log(him.Him_0);
    }
}
  • getset关键字允许设置变量的可读可写属性,同时内部还能像函数一样添加运算和调用其他属性和方法。两个关键字还可以只写其一。

Unity中的一些实验

  1. 脚本①没有需要执行的代码,不需要挂载到对象中也可以。

  2. 脚本②有需要执行的代码,需要挂载到对象中才可以执行。并可以调用脚本①,即使脚本①没有挂载。

  3. 脚本①如果没继承父类MonoBehaviour,则无法挂载,挂载操作会报错显示无法运行。

  4. 注意!!脚本①如果有继承父类MonoBehaviour,则脚本②调用时需要使用gameObject.AddComponent<>()。不然运行时会有一个警告,You are trying to create a MonoBehaviour using the 'new' keyword. This is not allowed. 《unity you are trying to create a monobehaviour using the ‘new’ keyword Code Example (codegrepper.com)

  5. 注意!!脚本①中的赋值him_0 = value,不要写错成Him_0 = value,会导致循环调用报错:栈溢出。StackOverflowException: The requested operation caused a stack overflow.c# - StackOverflowException: The requested operation caused a stack overflow - Stack Overflow

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值