Reputation: 3863
I have 2 object instances of same type. (To be precise this is Unity3D's AudioSource
) I need to apply some action like initializing, destroying, etc to both, so I think storing them in an array would be a good idea so I can iterate.
AudioSource[] audioSources = new AudioSource[2];
With this I can foreach
on the array and write initializing code and other common tasks only once.
But these two instances serves different purpose, say, the first is an AudioSource for BGM and the second is for SFX. This way the code will be more readable and I can still iterate over two instances by using the array.
So I think I should give an alternate names for each instance like bgmSource
and sfxSource
. I'd like to ask that is this the correct approach?
AudioSource bgmSource = audioSources[0];
AudioSource sfxSource = audioSources[1];
Upvotes: 0
Views: 185
Reputation: 44
Another solution is using a Dictionary, its not very suitable for such small arrays but it can help you distinct between objects without using second variable to store reference to the one in the array.
For example:
Dictionary< string, AudioSource > audioSources;
audioSources = new Dictionary<string, AudioSource>
{
"BGM_SOURCE", new AudioSource(),
"SFX_SOURCE", new AudioSource()
};
Then you can also use enum for keeping track of dictionary keys instead of using string/constant values:
// Enum declaration
enum AudioSourceNames
{
BGM_SOURCE,
SFX_SOURCE
}
// Called before first update
public void Start()
{
// Dictionary declaration
Dictionary< int, AudioSource > audioSources;
audioSources = new Dictionary< int, AudioSource >
{
( int )BGM_SOURCE, new AudioSource(),
( int )SFX_SOURCE, new AudioSource()
};
// Accessing the dictionary
audioSources[ ( int )AudioSourceNames.BGM_SOURCE ].Play();
}
BTW: You can use the enumarator technique with array, this way you won't have to remember each AudioSource index in the array
Upvotes: 1
Reputation: 3430
Well, it's legal. It's just a matter of preference/design. I would say that you could put them in a Dictionary of some sort. So you can properly label them through a key
. That way you won't need to remember that [0]
is bgmSource
and [1]
is sfxSource
.
Upvotes: 1
Reputation: 5163
From my point of view your solution seem good.
initializing code and other common tasks only once
The code for these things is hopefully in AudioSource, isn't it?
Upvotes: 1