LoginSignup
19
19

More than 3 years have passed since last update.

[Unityで学ぶC#] 12 static

Last updated at Posted at 2017-03-04
1 / 7

staticとは

インスタンスごとではなく, クラスが直接持っている,1つしかない値です.

まずはスコア等1つしかないものをこれを使って実装してみましょう。


サンプル

まずはScoreクラスを作りましょう.
スクリーンショット 2017-03-05 3.03.25.png


サンプル

別の適当なクラスを作ります.
スクリーンショット 2017-03-05 3.07.49.png


staticのここがすごい

クラス名.変数名でどこからでもアクセスすることができる.

Unityだと通常他のスクリプトと連携するためにはpublic や GetComponentで取得する必要があるが,
それがいらない.


関数も同様に使うことができる.

public static void AddScore(int point){
    score += point;
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Example12 : MonoBehaviour {

    void Start () {
        Score.score = 10;
        Score.AddScore (12);
        Debug.Log (Score.score);
    }
}

おわり

19
19
1

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
19
19