I recently started using properties to encapsulate my private variables, and I have a question about best practices when encapsulating a private variable.
Right now I have the following, which works fine:
public GameObject playerGO;
private Transform bikeCollidersParent;
public Transform BikeColParent
{
get {
if (bikeCollidersParent == null)
{
bikeCollidersParent = new GameObject("BikeColliders").transform;
bikeCollidersParent.parent = playerGO.transform;
if (bikeCollidersParent == null)
print("No Colliders Found in player object");
}
return this.bikeCollidersParent;
}
set {
bikeCollidersParent = value;
}
}
void Awake () {
// Cache player gameObject
playerGO = GameObject.FindWithTag("Bike");
// Cache player's transform components
foreach (Transform t in playerGO.GetComponentsInChildren<Transform>())
{
if (t.name == "Collider")
{
bikeCollidersParent = t;
}
}
As you can see, I set the value of "bikeCollidersParent" in Awake(), and if nothing is found in Awake(), I create a new GameObject within the "get{}" accessor in the property.
Now I'd like to keep everything related to the "bikeCollidersParent" in the "get{}" accessor, so I can do that with the following code:
public GameObject playerGO;
private Transform bikeCollidersParent;
public Transform BikeColParent
{
get {
if (bikeCollidersParent == null)
{
// Cache player's transform components
foreach (Transform t in playerGO.GetComponentsInChildren<Transform>())
{
if (t.name == "Collider")
{
bikeCollidersParent = t;
}
if (bikeCollidersParent == null)
{
bikeCollidersParent = new GameObject("BikeColliders").transform;
bikeCollidersParent.parent = playerGO.transform;
if (bikeCollidersParent == null)
print("No Colliders Found in player object");
}
}
}
return this.bikeCollidersParent;
}
set {
bikeCollidersParent = value;
}
}
void Awake () {
// Cache player gameObject
playerGO = GameObject.FindWithTag("Bike");
}
Which of these 2 blocks of code is the most appropriate version? What's the difference between putting the "foreach()" loop in "Awake()" and putting it within the "get{}" accessor?
Thanks in advance for any help!
Stephane
Hey Mike, thanks for the answer. When tou say "you'll only need to calculate the parent if you try access it", you're talking about my second implementation, correct? If i understand correctly, putting the "foreach" loop in Awake() automatically calculates the parent, but if I put it in the "get{}" accessor, it doesn't get calculated until I try to access it, for example, from another script's Awake() or Start(), is this correct? Thanks again
– ronronmxExactly right, yes.
– anon85704231