プロパティの作成

Tutorial

intermediate

+0XP

5 mins

(34)

Unity Technologies

プロパティの作成

プロパティを作成して、クラスのメンバー変数(フィールド)にアクセスする方法を学びます。

Languages available:

1. プロパティ

Player クラスのコード

using UnityEngine;
using System.Collections;

public class Player
{
    //メンバー変数は
 //フィールドとして参照できます。
    private int experience;

    //経験は基本的な財産です
    public int Experience
    {
        get
        {
            //他のコード
            return experience;
        }
        set
        {
            //他のコード
            experience = value;
        }
    }

    //レベルは、経験値
 //ポイントをプレーヤーのレベルに自動的に変換するプロパティです
    public int Level
    {
        get
        {
            return experience / 1000;
        }
        set
        {
            experience = value * 1000;
        }
    }

    //これは自動実装された
 //プロパティの例です
    public int Health{ get; set;}
}


Game クラスのコード

using UnityEngine;
using System.Collections;

public class Game : MonoBehaviour 
{
    void Start () 
    {
        Player myPlayer = new Player();

        //プロパティは変数と同じように使用できます
        myPlayer.Experience = 5;
        int x = myPlayer.Experience;
    }
}

Complete this Tutorial