using System.Collections.Generic; using UnityEngine; namespace UnityEditor.Tilemaps { /// /// This base class for PrefabBrushes that contains common functionality /// public class BasePrefabBrush : GridBrush { /// /// Anchor Point of the Instantiated Prefab in the cell when painting /// public Vector3 m_Anchor = new Vector3(0.5f, 0.5f, 0.5f); /// /// Gets all children of the parent Transform which are within the given Grid's cell position. /// /// Grid to determine cell position. /// Parent transform to get child Objects from. /// Cell position to get Objects from. /// A list of GameObjects within the given Grid's cell position. protected List GetObjectsInCell(GridLayout grid, Transform parent, Vector3Int position) { var results = new List(); var childCount = parent.childCount; var anchorCellOffset = Vector3Int.FloorToInt(m_Anchor); var cellSize = grid.cellSize; anchorCellOffset.x = cellSize.x == 0 ? 0 : anchorCellOffset.x; anchorCellOffset.y = cellSize.y == 0 ? 0 : anchorCellOffset.y; anchorCellOffset.z = cellSize.z == 0 ? 0 : anchorCellOffset.z; for (var i = 0; i < childCount; i++) { var child = parent.GetChild(i); if (position == grid.WorldToCell(child.position) - anchorCellOffset) { results.Add(child.gameObject); } } return results; } /// /// Instantiates a Prefab into the given Grid's cell position parented to the brush target. /// /// Grid to determine cell position. /// Target to instantiate child to. /// Cell position to instantiate to. /// Prefab to instantiate. protected void InstantiatePrefabInCell(GridLayout grid, GameObject brushTarget, Vector3Int position, GameObject prefab, Quaternion rotation = default) { var instance = (GameObject)PrefabUtility.InstantiatePrefab(prefab); if (instance != null) { Undo.MoveGameObjectToScene(instance, brushTarget.scene, "Paint Prefabs"); Undo.RegisterCreatedObjectUndo((Object)instance, "Paint Prefabs"); instance.transform.SetParent(brushTarget.transform); instance.transform.position = grid.LocalToWorld(grid.CellToLocalInterpolated(position + m_Anchor)); instance.transform.rotation = rotation; } } } /// /// The Base Brush Editor for a Prefab Brush. /// public class BasePrefabBrushEditor : GridBrushEditor { private SerializedProperty m_Anchor; /// /// SerializedObject representation of the target Prefab Brush /// protected SerializedObject m_SerializedObject; /// /// OnEnable for the BasePrefabBrushEditor /// protected override void OnEnable() { base.OnEnable(); m_SerializedObject = new SerializedObject(target); m_Anchor = m_SerializedObject.FindProperty("m_Anchor"); } /// /// Callback for painting the inspector GUI for the PrefabBrush in the Tile Palette. /// The PrefabBrush Editor overrides this to have a custom inspector for this Brush. /// public override void OnPaintInspectorGUI() { m_SerializedObject.UpdateIfRequiredOrScript(); EditorGUILayout.PropertyField(m_Anchor); m_SerializedObject.ApplyModifiedPropertiesWithoutUndo(); } } }