2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Unity C#のstatic,const,private,public

Posted at

SS 192.png じぶん用のメモ。まちがっているかも。更新中。

UnityのC#で変数を宣言するときのメモ

const

・変化しない値を定義する時に使用。
・宣言時に値を代入する必要がある。
・コンパイル時に定数(固定の数値)として扱われる。
・つまりコードの中で書き換えを指定できない。
・static readonly とだいたい同じ。(違いはこちらの記事を参照。)

static

・メモリを静的に確保。メモリ領域が静的なだけなので、数値は動的に変更できる。
・Unityではアプリケーションにただ1つだけ生成する変数。(インスタンス単位の生成ではない)
・どこからでも参照できる。
・ゲームのスコアなど、1個しかないパラメータに使う。

public(アクセス修飾子)

・アクセス制限なし。もっともゆるい。どこからでも参照できる。
・外部から[クラス名].[変数名]で取得できる。
・Unityのインスペクターに表示される。
・public static 〜 とするとインスペクターには表示されなくなる。
 (理由はインスペクターが担当するインスタンスに紐づかなくなるから?)

private(アクセス修飾子)

・同じ class 内または同じ struct 内のコードからのみアクセスできる。
・private関数にアクセスするときはプロパティを使う。
・[SerializeField] をつけておくとインスペクタ上から操作できる。

プロパティを利用したprivate変数へのアクセス

X_sample.cs
using UnityEngine;
using System;

public class X_sample : MonoBehaviour {
private int x = 1;
public int X{
        get{
            return x;
        }
        set{
           x = value;
       }
    }
}

のようにすると、外部からprivate int xの値を
a = X_sample.X;
のように取得することができ、

X_sample.X = 10;
のように書き込みができる。

#参考記事

2
0
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
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?