Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
This post has been wikified, any user with enough reputation can edit it.
avatar image
11
Question by ConsciousCoder · Oct 15, 2013 at 05:46 AM · c#getset

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);
    }
 }
 }


Comment
Add comment · Show 1
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Fattie · Oct 16, 2013 at 06:16 AM 1
Share

@conscious please TIC$$anonymous$$ AN ANSWER as you are the OP. it's the round TIC$$anonymous$$ symbol.

1 Reply

· Add your reply
  • Sort: 
avatar image
41
Best Answer

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.

Comment
Add comment · Show 20 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Fattie · Oct 15, 2013 at 08:28 AM 1
Share

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?

avatar image whydoidoit · Oct 15, 2013 at 08:59 AM 1
Share

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 ; }
avatar image fafase · Oct 15, 2013 at 09:09 AM 0
Share

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.

avatar image Fattie · Oct 15, 2013 at 09:10 AM 0
Share

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?)

avatar image whydoidoit · Oct 15, 2013 at 09:34 AM 1
Share

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.

Show more comments

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

19 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Are properties variables? 1 Answer

Multiple Cars not working 1 Answer

C# public parameter with custom get/set doesnt shown in the Inspector 4 Answers

Distribute terrain in zones 3 Answers

Are there differences between initializing at start and at declaration part 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges