需要访问数组中的特殊帧

时间:2016-10-01 08:48:24

标签: c# unity3d

在我的游戏中,我有一个对话框和图像面板,我想在每个角色上显示3-frames animation。我用这个脚本做到了:

public Texture[] frames;                // array of textures
public float framesPerSecond = 2.0f;    // delay between frames
RawImage image = null;

void Start()
{
    image = gameObject.GetComponent<RawImage>();
}

void Update()
{
    int index = (int)(Time.time * framesPerSecond) % frames.Length;
    image.texture = frames[index];
}

我为所有角色的所有图像都有一个数组。怎么说,我想从阵列中取出哪3张图片?像这样:

void Update()
{
    switch(currentCharacterName)
    {
        case "character1":
            // take elements 0 1 2 from array 'frames'
            image.texture = frames[index];
            break;
        case "character2":
            // take elements 3 4 5 from array 'frames'
            image.texture = frames[index];
            break;
    }
}

enter image description here

1 个答案:

答案 0 :(得分:1)

我希望我能正确理解你的问题。

string[] names = new[] {"name1", "name2", "name3"}; // sample array
void Update(){
    int index = names.indexOf(currentCharacterName);
    var framesByName = names.Skip(index * 3).Take(3).ToArray();
}

或者,如果将names数组更改为每个名称都有其相应索引的字典,则可以使其更快更优雅。

Dictionary<string, int> names = new {{"name1", 1}, {"name2", 2}, {"name3", 3}}; // Now you can directly access the index without using indexOf

但最优雅的解决方案是改变他们保存框架的方式:

public Dictionary<string, Texture[]> frames; // Here you can have pairs of character name and an array of its three textures..

通过这个,您可以直接访问所需的三个元素。