Question by
sonata0 · Aug 11, 2018 at 08:49 AM ·
unity 5getcomponentaudiosource
GetComponent AudioSource not working
AudioSource _audioSrc;
void Start()
{
_audioSrc = GetComponent<AudioSource>() ?? gameObject.AddComponent<AudioSource>();
}
I want to cache Audio Component to _audioSrc member, but above code doesn't work. I know 'RequireComponent' Attribute and that works better. anyone know what is missed?
Comment
Hi @sonata0 - Not sure what is going on with ?? operator, never used it - wasn't it part of .net 4.x? Anyway, you should be fine with: _audioSrc = GetComponent() != null ? GetComponent() : gameObject.AddComponent();