1. 程式人生 > >asset 資源配置檔案

asset 資源配置檔案

 在遊戲開發中,我們經常要對一些資料預先配置,一般可通過XML,Json配置. 還可以用Unity自帶的.Asset資源配置檔案配置資料,下面介紹一下如何靈活快速的建立.Asset檔案並使用.

Asset檔案可以直接配置如 GameObject、Sprite、AudioClip等高階的物件

直接上碼:

1.

[CreateAssetMenu(fileName = "AssetTest",menuName = "__Asset/AssetTest")]
public sealed class AssetTest : ScriptableObject {

    public int age;
    public float height;
    public GameObject obj;
    public Sprite sprite;
    public AudioClip audioClip;

}

2.在Asset目錄下建立Editor資料夾,建立指令碼

public class AssetTestEditor : Editor {

    private const string ConfigDir = "Assets/Editor/Resources/Config";
    private const string AssetTest= "AssetTest";
    private const string FileNameFull = AssetTest+ ".asset";

    [MenuItem("Test/Create .asset")]
    public static void Create() {
        AssetDatabase.StartAssetEditing();
        AssetTest assetTest;
        assetTest = ScriptableObject.CreateInstance<AssetTest>();
        AssetDatabase.CreateAsset(assetTest, ConfigDir + "/" + FileNameFull );
        assetTest.age = 10;
        assetTest.height = 5.0f;

        EditorUtility.SetDirty(assetTest);

        //更新本地版本
        AssetDatabase.StopAssetEditing();
        AssetDatabase.SaveAssets();
    }

    
}

在選單欄裡Test/Create .asset

現在你就可以通過ConfigDir路徑下找到你建立的.asset檔案

在建立一個指令碼用來測試,掛在場景的物件上

    AssetTest testConfig;
    string ConfigDir = "Assets/Editor/Resources/Config/";
    string ConfigFileName = "AssetTest.asset";
    // Use this for initialization
    void Start () {
        this.testConfig = AssetDatabase.LoadAssetAtPath<AssetTest>(ConfigDir + ConfigFileName);
        print("1:"+testConfig.age);
        this.testConfig.age = Random.Range(1,100);
        print("2:" + testConfig.age);
    }

這樣每次執行就會age就會改變新的值,不用儲存,裡面的值直接被修改了

附:你也可以通過WWW從伺服器上下載資料給本地.asset檔案賦值