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 ?
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:
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:
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:
(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
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:
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:
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:
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.
answered Oct 15, 2013 at 06:30 AM