#if UNITY_EDITOR
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System;

public class CreateSpiderEditorScript
{
    static GameObject prevSelection = null;
    [MenuItem("GameObject/Turn Into Spider Enemy", false, 0)]
    static void PlacePrefab()
    {
        if (prevSelection == Selection.activeGameObject) {
            return;
        }
        prevSelection = Selection.activeGameObject;

        // Load the prefab
        GameObject prefab = Resources.Load("SpiderEnemyLegs") as GameObject;
        if (prefab == null)
        {
            Debug.LogError("SpiderEnemyLegs not found");
            return;
        }
        GameObject[] copy = new GameObject[Selection.gameObjects.Length];
        Selection.gameObjects.CopyTo(copy, 0);

        foreach (GameObject obj in copy)
        {
            // Instantiate the prefab at the selected GameObject's position
            GameObject prefabInstance = (GameObject)PrefabUtility.InstantiatePrefab(prefab);
            Undo.RegisterCreatedObjectUndo(prefabInstance, "Place Prefab");

            // Match the position, rotation, and scale to the selected GameObject
            prefabInstance.transform.position = obj.transform.position;
            prefabInstance.transform.rotation = obj.transform.rotation;
            prefabInstance.transform.localScale = obj.transform.localScale;

            // Set the parent of the prefab instance to match the original GameObject's parent
            prefabInstance.transform.SetParent(obj.transform.parent, true);

            // Maintain the original GameObject's position in the hierarchy
            prefabInstance.transform.SetSiblingIndex(obj.transform.GetSiblingIndex());

            // Make the original GameObject a child of the instantiated prefab
            Undo.SetTransformParent(obj.transform, prefabInstance.transform, "Parent Original to Prefab");
            prefabInstance.transform.SetParent(null, true);


            prefabInstance.GetComponent<SpiderEnemy>().ParentSpider(obj.transform);
            prefabInstance.gameObject.name += " " + obj.name;
        }
    }

    [MenuItem("GameObject/Turn Into Spider Enemy", true)]
    static bool ValidatePlacePrefab()
    {
        return Selection.activeGameObject != null;
    }
}
#endif
