iLMS知識社群歷程檔登入
位置: 黃國哲 > Unity
1100826 ScriptableObject
by 黃國哲 2021-08-26 15:51:59, 回應(0), 人氣(401)
官方網頁


1.將按鈕掛上Spawner腳本
2.使用SpawnManagerScriptableObject數據創建資料物件
3.在按鈕選擇要產生的Prefab物件
4.在按鈕選擇要採用的SpawnManagerScriptableObject數據資料物件
5.按下按鈕後會看見畫面上在輸入的位置上產生所選擇的Prefab物件






using UnityEngine;

[CreateAssetMenu(fileName = "Data", menuName = "ScriptableObjects/SpawnManagerScriptableObject", order = 1)]
public class SpawnManagerScriptableObject : ScriptableObject
{
    public string prefabName;

    public int numberOfPrefabsToCreate;
    public Vector3[] spawnPoints;
}



using UnityEngine;

public class Spawner : MonoBehaviour
{
    // 要实例化的游戏对象。
    public GameObject entityToSpawn;

    //上面定义的 ScriptableObject 的一个实例。
    public SpawnManagerScriptableObject spawnManagerValues;

    //这将附加到创建的实体的名称,并在创建每个实体时递增。
    int instanceNumber = 1;

    public void Startbtn()
    {
        int currentSpawnPointIndex = 0;

        for (int i = 0; i < spawnManagerValues.numberOfPrefabsToCreate; i++)
        {
            //在当前生成点处创建预制件的实例。
            GameObject currentEntity = Instantiate(entityToSpawn, spawnManagerValues.spawnPoints[currentSpawnPointIndex], Quaternion.identity);

            //将实例化实体的名称设置为 ScriptableObject 中定义的字符串,然后为其附加一个唯一编号。
            currentEntity.name = spawnManagerValues.prefabName + instanceNumber;

            // 移动到下一个生成点索引。如果超出范围,则回到起始点。
            currentSpawnPointIndex = (currentSpawnPointIndex + 1) % spawnManagerValues.spawnPoints.Length;

            instanceNumber++;
        }
    }
}



回應