方法1:(透過方法存取)
◎ 類別(class)內容:
public class myCharacter {
private int _HP;
public int getHP(){ return _HP; }
public void setHP( int HP ){
if (HP < 0) { HP = 0; } // 限制 _HP 最小為 0
_HP = HP;
}
}
◎ 建立物件(object):
myCharacter npc = new myCharacter();
npc.setHP ( 96 );
print ( npc.getHP() );
方法2:(透過屬性存取)
◎ 類別(class)內容:
public class myCharacter {
private int _HP;
public int HP{
get { return _HP; }
set { if ( value < 0 ) { value = 0; } // value 為傳入的值
_HP = value; }
}
}
◎ 建立物件(object):
myCharacter npc = new myCharacter();
npc.HP = 33;
print ( npc.HP );
建議延伸閱讀:
>>
unity C# 語法教學入門
>>
Unity Script 常用語法教學(unity課程入門學習筆記)