介紹ScriptableObject,用來實現 文字遊戲的 state 流程.
特點:
1. 建立一個資料容器的樣板 template ,可以存放資料。
1.1 1. TextArea
2. store data out of script。 如果有一個包含script的Prefab,當 instantiate 那個 Prefab時,就會有復數的資料產生,但是使用ScriptableObject可以避免。
unity manual : ScriptableObject
範例一、
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu(menuName = "State")]
public class State : ScriptableObject {
[TextArea(14,10)] [SerializeField] string storyText;
}
1. CreateAssetMenu(menuName = "State") ,在Project窗口按下右鍵,出現可以創造 ScriptableObject的選項,名字是 State。
2. [TextArea(14,10)] : 在 inspector 的 打字區建立"多行"打字區,而非原本的很難閱讀的一行區域。
範例2 from Laser Defender:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[CreateAssetMenu(menuName = "Enemy Wave Config")]
public class WaveConfig : ScriptableObject
{
[SerializeField] GameObject enemyPrefab;
[SerializeField] GameObject pathPrefab;
[SerializeField] float timeBetweenSpawns = 0.5f;
[SerializeField] float spawnRandomFactor = 0.3f;
[SerializeField] int numberOfEnemies = 5;
[SerializeField] float moveSpeed = 2f;
#region Public Methods
public GameObject GetEnemyPrefab()
{
return enemyPrefab;
}
public GameObject GetPathPrefab()
{
return pathPrefab;
}
public float GetTimeBetweenSpawns()
{
return timeBetweenSpawns;
}
public float GetSpawnRandomFactor()
{
return spawnRandomFactor;
}
public int GetNumberOfEnemies()
{
return numberOfEnemies;
}
public float GetMoveSpeed()
{
return moveSpeed;
}
#endregion
}