I have problem about encapsulation. I have learned that in Java and as far as I know it works the same way in C# but in Unity It does not work. I will show you.
I am just trying to apply encapsulation but I am given these error messages. I want to create an “AnotherClass” instance and want to change the “apple” value via “setApple” method. I do this in java and C# without having any problems but in Mono I am given this error message: “Apple does not exist in the current context.”
using UnityEngine;
using System.Collections;
public class AnotherClass {
private int apple;
public void setApple(int app) {
apple = app;
}
public int getApple() {
return apple;
}
}
Was able to instantiate an object from the class in another script.
using UnityEngine;
using System.Collections;
public class Blah : MonoBehaviour {
void Start () {
AnotherClass apple = new AnotherClass();
apple.setApple(5);
}
}
I feel the need to point out that C# has a grammar structure for more easily implementing properties.
using UnityEngine;
using System.Collections;
public class AnotherClass {
private int m_apple;
public int Apple {
get {
return m_apple;
}
set {
m_apple = value;
}
}
}
Using them is like this.
using UnityEngine;
using System.Collections;
public class Blah : MonoBehaviour {
void Start () {
AnotherClass apple = new AnotherClass();
apple.Apple = 5;
Debug.Log(apple.Apple.ToString());
}
}
It’s because properties are methods, they don’t necessarily have data behind them.
Example:
public class Vector2
{
private float _x;
private float _y;
public float X
{
get { return _x; }
set { _x = value; }
}
public float Y
{
get { return _y; }
set { _y = value; }
}
public float Magnitude
{
get { return Math.Sqrt(_x * _x + _y * _y); }
set
{
var l = Math.Sqrt(_x * _x + _y * _y);
_x = value * _x / l;
_y = value * _y / l;
}
}
}
What is Magnitude? How do we display Magnitude? How is Magnitude serialized? Updating Magnitude sets 2 other fields which reflects a change in those properites.
The inspector displays the data that can be serialized on the object. And that data is represented as the fields.
Of course inspectors CAN show properties, you write a custom inspector to do so, so that way you decide what properties show and what don’t.