0

我有 2 个相同类型的对象实例。(准确地说,这是 Unity3D 的AudioSource)我需要对两者都应用一些操作,如初始化、销毁等,所以我认为将它们存储在数组中是一个好主意,这样我就可以迭代了。

AudioSource[] audioSources = new AudioSource[2];

有了这个,我可以foreach在数组上只写一次初始化代码和其他常见任务。

但是这两个实例有不同的用途,例如,第一个是用于 BGM 的 AudioSource,第二个是用于 SFX。这样代码将更具可读性,我仍然可以使用数组遍历两个实例。

所以我认为我应该为每个实例提供一个备用名称,例如bgmSourceand sfxSource。我想问这是正确的方法吗?

AudioSource bgmSource = audioSources[0];
AudioSource sfxSource = audioSources[1];
4

3 回答 3

1

另一种解决方案是使用字典,它不太适合如此小的数组,但它可以帮助您区分对象,而无需使用第二个变量来存储对数组中对象的引用。

例如:

    Dictionary< string, AudioSource > audioSources;

    audioSources = new Dictionary<string, AudioSource> 
    { 
        "BGM_SOURCE", new AudioSource(),
        "SFX_SOURCE", new AudioSource()
    };

然后,您还可以使用枚举来跟踪字典键,而不是使用字符串/常量值:

// 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();
}

顺便说一句:您可以将枚举器技术与数组一起使用,这样您就不必记住数组中的每个 AudioSource 索引

于 2013-06-10T18:03:18.333 回答
1

从我的角度来看,您的解决方案似乎不错。

只初始化一次代码和其他常见任务

这些东西的代码希望在 AudioSource 中,不是吗?

于 2013-06-10T05:27:27.213 回答
1

嗯,这是合法的。这只是偏好/设计的问题。我会说你可以把它们放在某种字典里。因此,您可以通过key. 这样你就不需要记住[0]isbgmSource[1]is sfxSource

于 2013-06-10T05:29:38.313 回答