【Unity】.asset资源文件使用
ScriptableObject 简单用途
ScriptableObject 可以实现类似Xml的功能进行数据配置,也可进行数据的保存处理,将数据以资源的形式进行保存。下面进行脚本代码编写
创建.asset资源文件
1.新建1个类,继承ScriptableObject
2.类名前加入标签,可实现Unity菜单栏的添加
3.Unity中点击脚本创建的菜单生成资源文件
4.将资源文件放入Resources文件目录下
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu(fileName = "TestConfig",menuName ="CreatTestConfig",order =0)]
public class TestConfig : ScriptableObject
{
}
编写.asset资源文件
1.编写资源文件的配置类容
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu(fileName = "TestConfig",menuName ="CreatTestConfig",order =0)]
public class TestConfig : ScriptableObject
{
public List<TestData> Config = new List<TestData>();
}
[System.Serializable]
public struct TestData
{
public string stringValue1;
public int IntValue2;
public bool boolValue3;
public float floatValue4;
public double doubleValue5;
}
由上面的代码可以进行资源文件的配置
实现对外访问接口
1.进行单例访问接口编写
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu(fileName = "TestConfig",menuName ="CreatTestConfig",order =0)]
public class TestConfig : ScriptableObject
{
private static TestConfig _instance;
public static TestConfig Instance
{
get
{
if (_instance == null)
{
_instance = LoadAbConfig();
if (_instance == null)
{
Debug.LogError("当前要加载的资源文件不存在。");
}
}
return _instance;
}
}
public static TestConfig LoadAbConfig()
{
return Resources.Load("TestConfig") as TestConfig;
}
public List<TestData> Config = new List<TestData>();
}
[System.Serializable]
public struct TestData
{
public string stringValue1;
public int IntValue2;
public bool boolValue3;
public float floatValue4;
public double doubleValue5;
}
以上步骤完成后,即成功制作了1个简单的资源文件,可进行数据的存储。
完整代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu(fileName = "TestConfig",menuName ="CreatTestConfig",order =0)]
public class TestConfig : ScriptableObject
{
private static TestConfig _instance;
public static TestConfig Instance
{
get
{
if (_instance == null)
{
_instance = LoadAbConfig();
if (_instance == null)
{
Debug.LogError("当前要加载的资源文件不存在。");
}
}
return _instance;
}
}
public static TestConfig LoadAbConfig()
{
return Resources.Load("TestConfig") as TestConfig;
}
public List<TestData> Config = new List<TestData>();
}
[System.Serializable]
public struct TestData
{
public string stringValue1;
public int IntValue2;
public bool boolValue3;
public float floatValue4;
public double doubleValue5;
}