- Home /
Are there differences between initializing at start and at declaration part
What are the differences between
private Rigidbody rb { get { return GetComponent<Rigidbody> (); } set { rb = value; } }
and
private Rigidbody rb;
void Start () {
rb = GetComponent<RigidBody>();
}
They do pretty much the same, or not? Which you prefer and why?
$$anonymous$$ostly, the property case would look for the component each time you call it, the second part would look for it in the start, then the reference is assigned for any use. That is considering the property may create a infinite loop as mentioned in the answer.
Answer by IgorAherne · Jan 30, 2017 at 12:39 AM
private Rigidbody rb { get { return GetComponent (); } set { rb = value; } }
The above statement is called a "Property"
This one in particular is written incorrectly. It's called rb
Notice what will happen when you try to assign rb a value:
rb
becomes equal to a value, - but oh wait, rb
is a property, so let's invoke "set" on it. Fine, rb
becomes equal to a value, - but oh wait, rb
is a property, so let's invoke "set" on it.... This results in a recursion.
The correct way to do this would be
private Rigidbody myPrivateRigidbody = null;//notice, private.
public Rigidbody rb {get{return myPrivateRigidbody;} } //notice, no set here, and it's public.
void Start(){
//we can access our private variable, others will have to use property, which only has getter
myPrivateRigidbody = null;
}
Basically, set allows you to assign the incoming value to anything that was declared before (never to a member variable itself, as shown in the above example)
get does the opposite. Get fetches the value from somewhere, then provides it, similar to how a function would.
So they are pretty much like Rigidbody getSomeValue(){return myPrivateRB;}
or void setSomeValue(Rigidbody value){myPrivateRB = value};
As you can see, properties are very much like functions, but can be used like normal variables, without the () brackets
Your answer
Follow this Question
Related Questions
Initialising List array for use in a custom Editor 1 Answer
When to use SETters and GETters 2 Answers
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
What are these things doing in C#? 3 Answers