天天看點

Unity:資源加載,路徑拼接技巧,代碼控制動畫的播放,簡版

路徑拼接技巧:

string path = string.Format("{0}{1}", "Prefabs/huowu/huowu0", i + 1);

通過資源加載的方式,加載精靈圖檔,用代碼控制遊戲對象身上的精靈圖檔,已達到播放動畫,控制遊戲對象動作的效果.​

public class Huowu : MonoBehaviour
{
    // 用來存儲Sprite 2D圖像
    List<GameObject> HuoWuList = new List<GameObject>();

    int picture = 9;

    GameObject huowuPrefabs;

    private void Awake()
    {
        for (int i = 0; i < picture; i++)
        {
            // 加載預制體
            string path = string.Format("{0}{1}", "Prefabs/huowu/huowu0", i + 1);   //建立路徑
            huowuPrefabs = Resources.Load(path) as GameObject;                      //加載該路徑下的遊戲對象
            // 加入集合
            HuoWuList.Add(huowuPrefabs);
        }
    }

    private void Start()
    {
        InvokeRepeating("Idel", 0f, 0.1f);
    }

    int index = 0;
    void Idel()
    {
        if (index < picture)
        {
            // 擷取火舞身上的 Sprite
            transform.GetComponent<SpriteRenderer>().sprite = HuoWuList[index].GetComponent<SpriteRenderer>().sprite;
            index++;
        }
        else
        {
            index = 0;
        }
    }

}
           

繼續閱讀