Properties

Vérifié avec version: 4.1

-

Difficulté: Intermédiaire

How to create properties to access the member variables (fields) in a class.

Properties

Intermédiaire Scripting

Player

Code snippet

using UnityEngine;
using System.Collections;
public class Player
{
//Member variables can be referred to as
//fields.
private int experience;
//Experience is a basic property
public int Experience
{
get
{
//Some other code
return experience;
}
set
{
//Some other code
experience = value;
}
}
//Level is a property that converts experience
//points into the leve of a player automatically
public int Level
{
get
{
return experience / 1000;
}
set
{
experience = value * 1000;
}
}
//This is an example of an auto-implemented
//property
public int Health{ get; set;}
}

#pragma strict
public class Player
{
//Member variables can be referred to as
//fields.
var experience : int;
//Experience is a basic property
public function get Experience() : int
{
return experience;
}
public function set Experience(value : int)
{
experience = value;
}
//Level is a property that converts experience
//points into the leve of a player automatically
public function get Level() : int
{
return experience / 1000;
}
public function set Level(value : int)
{
experience = value * 1000;
}
//Auto-implemented properties are not a feature of the
//Javascript language.
}

import UnityEngine
import System.Collections
public class Player:
//Member variables can be referred to as
//fields.
private experience as int
//Experience is a basic property
public Experience as int:
get:
//Some other code
return experience
set:
//Some other code
experience = value
//Level is a property that converts experience
//points into the leve of a player automatically
public Level as int:
get:
return (experience / 1000)
set:
experience = (value * 1000)
//This is an example of an auto-implemented
//property
public Health as int:
get:
pass
set:
pass

Game

Code snippet

using UnityEngine;
using System.Collections;
public class Game : MonoBehaviour
{
void Start ()
{
Player myPlayer = new Player();
//Properties can be used just like variables
myPlayer.Experience = 5;
int x = myPlayer.Experience;
}
}