LoginSignup
74
69

More than 5 years have passed since last update.

他スクリプトから変数の値を取得する.(ゲッター,セッター)

Posted at

プレイヤーの弾の残り数など,他のスクリプトの変数の値が欲しいことがある.
その方法について紹介する.

PlayerScript.cs
private int bulletCount = 5;

この,bulletCountを取得したいとする.
方法は3つある.
1. publicにする.
2. プロパティーを使う.
3. それ用の関数を作る.

それぞれ紹介するが,おすすめは,2のプロパティーである.

publicで取得

PlayerScript.cs
public int bulletCount = 5;

private ではなく,public を使用する.

OtherScript.cs
public PlayerScript playerScript;

void Start(){
    int bCount;
    bCount = playerScript.bulletCount;
    Debug.Log(bCount); //5
}

playerScript.bulletCountという形で取得することができる.

問題点

  • 外部から値を入力できてしまうため,バグの原因になる.

プロパティーを使う.

PlayerScript.cs
private int bulletCount = 5;
//プロパティー
public int BulletCount{
    get{ return this.bulletCount; }  //取得用
    private set{ this.bulletCount = value; } //値入力用
}

setの方にはprivateをつけることで,他のスクリプトからの入力はできないようにする.

OtherScript.cs
public PlayerScript playerScript;

void Start(){
    int bCount;
    bCount = playerScript.BulletCount;
    Debug.Log(bCount); //5
}

取得の方はあまり変わらない.

問題点

  • 初心者にとっては何のためにやるのかわからない.

関数を作る.

PlayerScript.cs
private int bulletCount = 5;
//取得用関数
public int GetBulletCount(){
    return bulletCount;
}

取得用の関数を作る.関数の頭にGetを作るのが主.
逆に値入力の場合はSetがつけられることが多い.SetBulletCount

OtherScript.cs
public PlayerScript playerScript;

void Start(){
    int bCount;
    bCount = playerScript.GetBulletCount();
    Debug.Log(bCount); //5
}

この方法でもバグは起こりにくいため,
こっちの方法でも問題はない.

取得の際に処理を行う場合はこれでもいいと思う.

問題点

  • 長い
74
69
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
74
69