- Home /
c# setter/getters
Hi I'm coming from a Java background. I cant find many resources on c# getters/setters in unity.
I have prefabs with the Block script attached to each. Each prefab is loaded into the MyBlocks[]
I just cant get/mod the values from the Block class in the class Player. So I'm really wondering how do c# setters and getters work in unity especially if I want to get/modify a private value from a class ?
public class Block : MonoBehaviour
{
[SerializeField]
private bool b = false;
public bool getB()
{
get{return b;}
}
}
public class Player : MonoBehaviour
{
public Block[] blockList;
public int size = 6;
public Block[] MyBlocks;
void start()
{
blockList = new Block[size];
for(int i = 0; i < size; i++)
{
int RandomNumber = Random.Range (0, MyBlocks.Length);
Instantiate(MyBlocks[RandomNumber],
MyBlocks[RandomNumber].transform.position ,
MyBlocks[RandomNumber].transform.rotation);
blockList[i] = MyBlocks[RandomNumber];
blockList[i].b = true;
Debug.Log("i: " + i + " " + blockList[i].b);
}
}
}
@conscious please TIC$$anonymous$$ AN ANSWER as you are the OP. it's the round TIC$$anonymous$$ symbol.
Answer by Hoeloe · Oct 15, 2013 at 06:30 AM
C# has a system for getters and setters called Properties that Java doesn't (I probably don't need to tell you that Java =/= Javascript, but it seems to be a common mistake). These are a really neat way of controlling variables, because they abstract away from using explicit "getX()" and "setX()" methods, allowing them to be used similarly to a regular variable. In terms of actual execution, it is essentially running a method call each time you use it, but it does make the code cleaner. Let's take an example. In Java, you would write something like this:
public int getX()
{
return x;
}
public void setX(int newX)
{
if(newX < 0)
x = 0;
else
x = newX;
}
This is a simple getter and setter in Java (and, coincidentally, also valid C#), which constrains an integer to be positive, clamping negative inputs to 0. This allows you to use it in this manner:
setX(getX()+4);
This will increase the value by 4. This is how getters and setters work in Java, and they can be used this way in C#, too. However, C# has a neater way of doing it. This is the same getter and setter written in C# using Properties:
public int X
{
get { return x; }
set
{
if(value < 0)
x = 0;
else
x = value;
}
}
This wraps the getter and setter into one item, allowing you to use the value in a more natural way. Instead of the (frankly rather ugly) code I used with the Java example to add 4 to the variable, instead we can do this:
X += 4;
(Note that the X here is capitalised, because X is the property, which is distinct from x, which is a variable.) This essentially runs the same code as above, but it's much neater, and easier to understand what's going on. The value
keyword is used to access the implicit argument of the set method, so you don't have to worry about explicitly defining it. You can also do things like this:
public int Y
{
get { return y; }
private set { y = value; }
}
Which will allow only the parent class to write to this property, but anyone to read it (which is incredibly useful in a lot of situations). And:
public int Z
{
get { return z; }
}
Which creates a read-only property, so that no-one can write to it. This is most useful if you're returning the result of a calculation, rather than just a variable (note that the get block can contain more than just a return statement, as it is essentially just a method that returns the type that the property is defined to have, you can execute arbitrary code in there, as long as it obeys the rules of the language, of course).
Finally, there is also the implicit property:
public int A
{
get; set;
}
This implicitly creates a variable for the property to read and write to. In this instance, it would work in exactly the same way as a public variable, but you can use access modifiers etc., as above, to alter how you can access the property. For example:
public int B
{
get; private set;
}
I hope this has given you a bit of an insight into how properties work. It's worth remembering that, though these look like variables when you use them, they are not variables - they are an abstraction for getters and setters, and so when you access a property, you are calling a method, not accessing a variable. Performance-wise, this makes them less efficient than variables, but more efficient than separate getter and setter methods, as they are easier for the compiler to optimise.
Hi Hoe, a very generous answer, I have three follow-up questions:
In this code ExampleA:
public int A
{
get; set;
}
In c#, is is true that, this is indeed absolutely identical to just saying "public int A;" To rephrase that, is it true there is absolutely no advantage to typing literally that code block ExampleA. (Assu$$anonymous$$g you DON'T even set one of them private, etc - so exactly that code block.)
Secondly and similarly, here is code ExampleB:
public Transform Ship
{
get
{
return _ship;
}
set
{
_ship = value;
}
}
which I often see programmers using. $$anonymous$$y question (2) is it true that ExampleB is, indeed, utterly identical in every way to ExampleA. And question (3), indeed, would you say it is absolutely, totally, exactly the case that all of ExampleB could simply be replaced by a variable "public Transform Ship;"
(You could phrase it this way in a word .... if you saw a programmer working for you, doing precisely ExampleA above and ExampleB above, would you just replace them with a simple variable declaration? Or am I missing something about c#?)
What do you think?
The primary reason for short property syntax in .NET is that XA$$anonymous$$L requires properties and not fields (the exact opposite of Unity Inspector!) You need a lot of properties with XA$$anonymous$$L!
Secondly, in Unity the primary reason for writing short property syntax is to create a readonly property that you might later override, or a property that can only be set by decendants and not callers:
public int A { get; protected set; }
public virtual int A { get; set ; }
Just a side note on coding convention regarding properties, @Hoeloe you mention that the property name is capitalized. The way you say it sounds like it is always as such. It is true almost everywhere in the .NET world but Unity.
The properties from .NET keep the convention
Array.Length;
while those from Unity do not:
Screen.width;
Vector.magnitude
So it can get confusing sometimes thinking you are facing a variable and it happens to be a property...
Still the whole thing you say is right.
Thanks! but ... What the heck is XA$$anonymous$$L man ??
(Regarding your second paragraph: for sure (astonishingly) I utterly understand that; my question is when you DON'T use any qualifier whatsoever, then, in fact, is it utterly pointless and the code should be changed to a variable and the programmer in question sacked?)
XA$$anonymous$$L it's what Silverlight and WPF and therefore most of windows uses to build UI these days.
I can't think of a reason for defining a property when a field would do unless one of the techniques is used to modify default behaviour - or perhaps there is some reflection framework that expects properties.
I wish Unity supported properties. Would make a bunch of Update functions irrelevant for me.