Newer
Older
Hierarchical-Task-Network-Unity-3D / Assets / Scripts / Environment / PositionsData.cs
using UnityEngine;
using UnityEditor;
using System.Collections.Generic;

/// <summary>
/// This class get GameObjects Positions to a scriptable object
/// </summary>
public class PositionsData : MonoBehaviour
{
    [SerializeField] private List<Transform> objectsToCapture;
    [SerializeField] private Transform origin; // Optional: For relative positions

    public Positions positionsAsset; // optional existing asset to overwrite

    [ContextMenu("Extract Positions to ScriptableObject")]
    public void ExtractPositions()
    {
        if (objectsToCapture == null || objectsToCapture.Count == 0)
        {
            Debug.LogWarning("No objects to extract.");
            return;
        }

        List<Vector3> extracted = new();

        foreach (var obj in objectsToCapture)
        {
            if (obj == null) continue;
            Vector3 pos = origin ? origin.InverseTransformPoint(obj.position) : obj.position;
            extracted.Add(pos);
        }

        Positions newAsset = positionsAsset;

        if (newAsset == null)
        {
            newAsset = ScriptableObject.CreateInstance<Positions>();
            string path = EditorUtility.SaveFilePanelInProject("Save Positions", "new Positions", "asset", "Save positions to asset");
            if (string.IsNullOrEmpty(path)) return;
            AssetDatabase.CreateAsset(newAsset, path);
        }

        newAsset.list = extracted.ToArray();
        EditorUtility.SetDirty(newAsset);
        AssetDatabase.SaveAssets();

        Debug.Log("Saved " + extracted.Count + " positions to " + AssetDatabase.GetAssetPath(newAsset));
    }
}