Declaring AudioSource variable

In the course we declare a variable for audio

  AudioSource myAudioSource;

then, in the start() method we initialize it
myAudioSource = GetComponent();

Why do we initialize in start() method? Why can’t we declare and initialize at the same time like this

AudioSource myAudioSource = GetComponent();

1 Like

You declare it at the top of the script so it can be used throughout the entire script. Declaring it in the Start() method would make it a local variable and you’d only be able to use it inside that method, that’s why it was declared at the top of the script and then got assigned in the Start() method.

I understand the scope for the variable is either going to be local or global depending on where it is declared. I’m mainly asking about the initialization of the variable. I messed around with the code and the only thing that I could find was the variable value at the start of the game. From what I can tell when it’s initialized in the start() method the value will always be “this” value. When it’s initialized outside of the start() method then it can be modified, through the inspector for example.

Unless you change it with code later yes it will remain the same.

The reason you are able to adjust the other variables in the inspector after declaring them at the top of the script is because they are either.

Example: [SerializedField] int or Public int.

Which in short makes them visible to the inspector.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms