Getter and Setter Question!

Hi Unity Forums! I just stumbled over Csharp getters and setters for the first the ever, as someone used them in a tutorial for creating a healthbar. I have a little bit of background using Java, and c++ so I already understand those getters and setters. Made a calculator etc,etc, nothing huge though.

In One script I have these functions.

public float MaxValue {
        get;
        set; 
    }

    public float Value
    {
        set{
            fillAmount = Map(value, 0, MaxValue, 0, 1); 
        }

    }

According to a video I watched on this subject
get; and set; is the same as get{return MaxValue}, and set{MaxValue = value;}

But then I get a different result. I don’t want to copy and paste my whole code unless someone asks for it, as it quite big. Basically, the health does not move.

It seems like these type of getters and setters are used to prevent too many variables. Is this true?

Because I do not want to make another post for such a small question I am going to edit in another question right here:

In one of my scripts I have a variable like this:
private Stat health;

I also have the same class public class Stat{}

This class is not attached anywhere (Any object in the game) and that confuses me, yet it still works. What happens when I build the game? So if I have a lots of objects downloaded into my project, and I don’t use them are they also just gonna sit there and take up space when I build the game? I thought only what was in the screen was going to be made as game.

This:

public float MaxValue
{
    get;
    set;
}

Would be the same as this:

private float _maxValue;

public float MaxValue
{
    get { return _maxValue; }
    set { _maxValue = value; }
}

But it is obviously shorter to write down. (Which is what I believe the only advantage (not 100% sure), the disadvantags being that you can’t do anything in the getter/setter yourself)

When you set the inspector to Debug in the right top, you can also see MaxValue his backed field in the inspector. (If you use the get; and set;)

I’m not sure what you mean with ‘different result’. As in different result opposed to what? :stuck_out_tongue:

And with the second question, not sure what the question is, but I hope I answer it with this response :stuck_out_tongue:

With not being linked to anything you mean that it’s not a MonoBehaviour but just a plain old C# class? Ye you can do that. Note that Serializing them in the inspector can be a pain depending on what you want. But you can use them ofcourse, You can basically use everything from the System namespace of which no class is written with Unity in mind ;). They just are referenced by your scripts, just like string, int, List, etc. are.