# GraphSelection

> Provides methods for implementing selection history handling in a GraphView.

## Definition

* **Type:** Class
* **Namespace:** [UnityEditor.Experimental.GraphView](/engine/6000.6/script-reference/unityeditor/experimental/graphview.md)
* **Assembly:** UnityEditor

```csharp
public class GraphSelection
```

## Remarks

Selection in a graph view is based on selecting [GraphElement](/engine/6000.6/script-reference/unityeditor/experimental/graphview/graphelement.md) objects (for example, nodes or edges). [GraphElement](/engine/6000.6/script-reference/unityeditor/experimental/graphview/graphelement.md) objects aren't regular Unity [Object](/engine/6000.6/script-reference/unityengine/object.md) classes, so they are not recorded in the regular [Selection](/engine/6000.6/script-reference/unityeditor/selection.md) history.

Use this helper class with the [Selection.RegisterCustomHandler](/engine/6000.6/script-reference/unityeditor/selection/registercustomhandler.md) and [Selection.SetCustomSelection](/engine/6000.6/script-reference/unityeditor/selection/setcustomselection.md) to implement selection history handling in a graph view.

The `GraphSelection` class contains a list of selected graph elements, typically their [VisualElement.viewDataKey](/engine/6000.6/script-reference/unityengine/uielements/visualelement/viewdatakey.md). The `GraphSelection` class is serializable, so you can use it with [EditorJsonUtility](/engine/6000.6/script-reference/unityeditor/editorjsonutility.md) to serialize to and from a JSON representation.

Use the [GraphSelection.ApplyToGraphView](/engine/6000.6/script-reference/unityeditor/experimental/graphview/graphselection/applytographview.md) method to apply the list of selected [GraphSelection.elements](/engine/6000.6/script-reference/unityeditor/experimental/graphview/graphselection/elements.md) to a graph view.

## Examples

```csharp
// Example of implementing selection history handling in a graph view.
// The graph below does not do anything useful, and it
// does not survive script recompilation (for simplicity purposes, the graph
// view edits a transient graph object, not an asset).
using UnityEngine;
using UnityEngine.UIElements;
using UnityEditor;
using UnityEditor.Experimental.GraphView;
using System.Collections.Generic;

public class SampleGraphView : GraphView
{
    const string kSelectionKey = "GraphViewSelectionHistoryExample";

    public SampleGraphView()
    {
        // Register a function that applies a stored selection
        // back to the graph view.
        Selection.RegisterCustomHandler(kSelectionKey, ApplySelection);
    }

    static void ApplySelection(string data, EntityId[] selectedEntityIDs)
    {
        // Deserialize selection from a JSON string.
        var info = GraphSelection.FromJson(data);
        if (info == null)
            return;

        // Selection history code focuses the relevant Editor window
        // before applying the selection history entry.
        // We'll want to apply selection to the graph view in that window.
        var window = EditorWindow.focusedWindow as GraphViewSelectionHistory;
        var gv = window?.graphView;
        if (gv == null)
            return;

        // Apply selection to the graph view.
        info.ApplyToGraphView(gv, null);
    }

    // Override selection related graph view methods, to record
    // the selection history entry.
    public override void AddToSelection(ISelectable selectable)
    {
        base.AddToSelection(selectable);
        UpdateSelectionHistory();
    }
    public override void RemoveFromSelection(ISelectable selectable)
    {
        base.RemoveFromSelection(selectable);
        UpdateSelectionHistory();
    }
    public override void ClearSelection()
    {
        base.ClearSelection();
        UpdateSelectionHistory();
    }

    // Record graph view selection into the selection history.
    void UpdateSelectionHistory()
    {
        var sel = new GraphSelection();
        foreach (var s in selection)
        {
            if (s is SampleNode node)
            {
                // Add view data key (which uniquely identifies a graph element)
                // into the selection object.
                sel.elements.Add(node.viewDataKey);
            }
        }
        if (sel.isEmpty)
            return;

        // Record the selection by serializing it into JSON.
        Selection.SetCustomSelection(kSelectionKey, EditorJsonUtility.ToJson(sel));
    }
}

// A simple node that only has a title.
public class SampleNode : Node
{
    public void InitializeNode(string text, float x, float y)
    {
        UseDefaultStyling();
        title = text;
        SetPosition(new Rect(x, y, 0, 0));
        MarkDirtyRepaint();
    }
}

// Editor window with the graph view. This does not do anything
// related to selection handling. This sets up the graph view
// and creates some nodes.
public class GraphViewSelectionHistory : EditorWindow
{
    [MenuItem("Window/GraphView Selection Example")]
    static void Init()
    {
        var window = EditorWindow.GetWindow<GraphViewSelectionHistory>();
        window.InitGraph();
        window.Show();
    }

    public GraphView graphView;

    void InitGraph()
    {
        rootVisualElement.Clear();

        graphView = new SampleGraphView();
        graphView.AddManipulator(new ContentDragger());
        graphView.AddManipulator(new SelectionDragger());
        graphView.AddManipulator(new RectangleSelector());
        graphView.AddManipulator(new ClickSelector());

        rootVisualElement.Add(graphView);
        graphView.StretchToParentSize();

        CreateNode("One", 20, 20);
        CreateNode("Two", 120, 20);
        CreateNode("Three", 20, 100);

        rootVisualElement.MarkDirtyRepaint();
    }

    void CreateNode(string text, float x, float y)
    {
        var node = new SampleNode();
        node.InitializeNode(text, x, y);
        graphView.AddElement(node);
    }
}
```

## Fields

| Value                                                                                                     | Description                                                                                                                                                     |
| --------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [elements](/engine/6000.6/script-reference/unityeditor/experimental/graphview/graphselection/elements.md) | Lists the data keys ([VisualElement.viewDataKey](/engine/6000.6/script-reference/unityengine/uielements/visualelement/viewdatakey.md)) of the selected element. |

## Constructors

| Constructor                                                                                                   | Description                                            |
| ------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------ |
| [GraphSelection()](/engine/6000.6/script-reference/unityeditor/experimental/graphview/graphselection/ctor.md) | Initializes and returns an instance of GraphSelection. |

## Properties

| Property                                                                                                | Description                                    |
| ------------------------------------------------------------------------------------------------------- | ---------------------------------------------- |
| [isEmpty](/engine/6000.6/script-reference/unityeditor/experimental/graphview/graphselection/isempty.md) | Returns true if the list of elements is empty. |

## Methods

| Method                                                                                                                    | Description                                            |
| ------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------ |
| [ApplyToGraphView](/engine/6000.6/script-reference/unityeditor/experimental/graphview/graphselection/applytographview.md) | Applies the list of selected elements to a graph view. |

## Static Methods

| Method                                                                                                    | Description                                               |
| --------------------------------------------------------------------------------------------------------- | --------------------------------------------------------- |
| [FromJson](/engine/6000.6/script-reference/unityeditor/experimental/graphview/graphselection/fromjson.md) | Deserializes a graph selection object from a JSON string. |
