I have a couple of these properties scattered about my code:
private Animator _anim;
public Animator anim
{
get
{
if (_anim == null)
{
_anim = GetComponent<Animator> ();
}
return _anim;
}
set
{
_anim = value;
}
}
I was wondering if it was possible to shorten this semantically, either through a custom field declaration like this:
public autogetprop Animator anim;
or through an attribute like this:
[AutoGetProp]
public Animator anim;
Basically, no - there's nothing to let you use automatically implemented properties with "just a bit" of custom code. You could shorten your code, though to:
public Animator Animator
{
get { return _anim ?? (_anim = GetComponent<Animator>()); }
set { _anim = value; }
}
Or you could write a GetComponent
method with a ref parameter, and use it like this:
public Animator Animator
{
get { return GetComponent(ref _anim)); }
set { _anim = value; }
}
where GetComponent
would be something like:
public T GetComponent(ref T existingValue)
{
return existingValue ?? (existingValue = GetComponent<T>());
}
If you don't like using the null-coalescing operator with side-effects like this, you could rewrite it as:
public T GetComponent(ref T existingValue)
{
if (existingValue == null)
{
existingValue = GetComponent<T>();
}
return existingValue;
}
Note that none of these solutions is thread-safe - just like your original code, if a second thread sets the property to null after the first thread has gone past the "is it null" check, the property can return null, which is presumably not the intention. (That's not even considering the memory model issues involved.) There are various ways of addressing this depending on what you want the semantics to be.
See more on this question at Stackoverflow