├── LICENSE.meta ├── Actions.meta ├── Editor.meta ├── Nodes.meta ├── Conditions.meta ├── GraphData.cs ├── Actions ├── SetVirtualCameraActive.cs.meta ├── Wait.cs.meta ├── DebugLog.cs.meta ├── PlayTimeline.cs.meta ├── SetGameObjectActive.cs.meta ├── SetGameObjectsActive.cs.meta ├── DisableAllVirtualCameras.cs.meta ├── SetGameObjectActiveDelayed.cs.meta ├── DebugLog.cs ├── Wait.cs ├── DisableAllVirtualCameras.cs ├── SetGameObjectsActive.cs ├── SetGameObjectActive.cs ├── SetGameObjectActiveDelayed.cs ├── SetVirtualCameraActive.cs └── PlayTimeline.cs ├── Node.cs.meta ├── Action.cs.meta ├── Condition.cs.meta ├── Graph.cs.meta ├── GraphData.cs.meta ├── Variable.cs.meta ├── Connection.cs.meta ├── Editor ├── GraphEditor.cs.meta ├── ActionGraphEditor.cs.meta ├── NodeInspector.cs.meta ├── ActionGraphInspector.cs.meta ├── GraphEditor.cs ├── NodeInspector.cs ├── ActionGraphInspector.cs └── ActionGraphEditor.cs ├── EditorGUIHelper.cs.meta ├── Nodes ├── TransitionNode.cs.meta └── TransitionNode.cs ├── UnityObjectConverter.cs.meta ├── Condition.cs ├── Connection.cs ├── README.md ├── Action.cs ├── Graph.cs ├── UnityObjectConverter.cs ├── Variable.cs ├── Node.cs ├── LICENSE └── EditorGUIHelper.cs /LICENSE.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: d607bfcb8cff9db4687889d2f2b27e93 3 | DefaultImporter: 4 | externalObjects: {} 5 | userData: 6 | assetBundleName: 7 | assetBundleVariant: 8 | -------------------------------------------------------------------------------- /Actions.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 3af92f9a676f61f4c93f369a9ab8837b 3 | folderAsset: yes 4 | timeCreated: 1523192854 5 | licenseType: Free 6 | DefaultImporter: 7 | externalObjects: {} 8 | userData: 9 | assetBundleName: 10 | assetBundleVariant: 11 | -------------------------------------------------------------------------------- /Editor.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 6278dcdc34fe2a74fafc13be57876e59 3 | folderAsset: yes 4 | timeCreated: 1523192854 5 | licenseType: Free 6 | DefaultImporter: 7 | externalObjects: {} 8 | userData: 9 | assetBundleName: 10 | assetBundleVariant: 11 | -------------------------------------------------------------------------------- /Nodes.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 1d475a4b7086bb8459d6833e15357f05 3 | folderAsset: yes 4 | timeCreated: 1523344604 5 | licenseType: Free 6 | DefaultImporter: 7 | externalObjects: {} 8 | userData: 9 | assetBundleName: 10 | assetBundleVariant: 11 | -------------------------------------------------------------------------------- /Conditions.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 8a8dc796ae9cc62439a5a2feaf6f4dc5 3 | folderAsset: yes 4 | timeCreated: 1523192854 5 | licenseType: Free 6 | DefaultImporter: 7 | externalObjects: {} 8 | userData: 9 | assetBundleName: 10 | assetBundleVariant: 11 | -------------------------------------------------------------------------------- /GraphData.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | using System.Collections.Generic; 3 | using UnityEngine; 4 | 5 | namespace ActionGraph 6 | { 7 | public class GraphData 8 | { 9 | public List Nodes = new List(); 10 | public int StartNodeIndex = 0; 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /Actions/SetVirtualCameraActive.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 4c9c392e10a4fe647b9148fb37970cd9 3 | MonoImporter: 4 | externalObjects: {} 5 | serializedVersion: 2 6 | defaultReferences: [] 7 | executionOrder: 0 8 | icon: {instanceID: 0} 9 | userData: 10 | assetBundleName: 11 | assetBundleVariant: 12 | -------------------------------------------------------------------------------- /Node.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: a78dc3b3756ef4f4e9a4b86c24691eec 3 | timeCreated: 1523192854 4 | licenseType: Free 5 | MonoImporter: 6 | externalObjects: {} 7 | serializedVersion: 2 8 | defaultReferences: [] 9 | executionOrder: 0 10 | icon: {instanceID: 0} 11 | userData: 12 | assetBundleName: 13 | assetBundleVariant: 14 | -------------------------------------------------------------------------------- /Action.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: c02e65a07c399d04e955c72d19d7a3dc 3 | timeCreated: 1523192854 4 | licenseType: Free 5 | MonoImporter: 6 | externalObjects: {} 7 | serializedVersion: 2 8 | defaultReferences: [] 9 | executionOrder: 0 10 | icon: {instanceID: 0} 11 | userData: 12 | assetBundleName: 13 | assetBundleVariant: 14 | -------------------------------------------------------------------------------- /Condition.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 262310428d7cb674aa660c2a33b8aa87 3 | timeCreated: 1523192854 4 | licenseType: Free 5 | MonoImporter: 6 | externalObjects: {} 7 | serializedVersion: 2 8 | defaultReferences: [] 9 | executionOrder: 0 10 | icon: {instanceID: 0} 11 | userData: 12 | assetBundleName: 13 | assetBundleVariant: 14 | -------------------------------------------------------------------------------- /Graph.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 0a0c94bce92af9746be8e252f4125f72 3 | timeCreated: 1523192854 4 | licenseType: Free 5 | MonoImporter: 6 | externalObjects: {} 7 | serializedVersion: 2 8 | defaultReferences: [] 9 | executionOrder: 0 10 | icon: {instanceID: 0} 11 | userData: 12 | assetBundleName: 13 | assetBundleVariant: 14 | -------------------------------------------------------------------------------- /GraphData.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 0f311b497e004f24fa983e941706d45d 3 | timeCreated: 1523192854 4 | licenseType: Free 5 | MonoImporter: 6 | externalObjects: {} 7 | serializedVersion: 2 8 | defaultReferences: [] 9 | executionOrder: 0 10 | icon: {instanceID: 0} 11 | userData: 12 | assetBundleName: 13 | assetBundleVariant: 14 | -------------------------------------------------------------------------------- /Variable.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 4f287e731c13fe245a86baa06ad45356 3 | timeCreated: 1523602090 4 | licenseType: Free 5 | MonoImporter: 6 | externalObjects: {} 7 | serializedVersion: 2 8 | defaultReferences: [] 9 | executionOrder: 0 10 | icon: {instanceID: 0} 11 | userData: 12 | assetBundleName: 13 | assetBundleVariant: 14 | -------------------------------------------------------------------------------- /Actions/Wait.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 77d64434f21ffe744828bd7a4efab403 3 | timeCreated: 1523192854 4 | licenseType: Free 5 | MonoImporter: 6 | externalObjects: {} 7 | serializedVersion: 2 8 | defaultReferences: [] 9 | executionOrder: 0 10 | icon: {instanceID: 0} 11 | userData: 12 | assetBundleName: 13 | assetBundleVariant: 14 | -------------------------------------------------------------------------------- /Connection.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 838958c1f5f19af49979e8dcd50627e1 3 | timeCreated: 1523863428 4 | licenseType: Free 5 | MonoImporter: 6 | externalObjects: {} 7 | serializedVersion: 2 8 | defaultReferences: [] 9 | executionOrder: 0 10 | icon: {instanceID: 0} 11 | userData: 12 | assetBundleName: 13 | assetBundleVariant: 14 | -------------------------------------------------------------------------------- /Actions/DebugLog.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: cb6a73df4f056ef41bcee0896ad755d5 3 | timeCreated: 1523192854 4 | licenseType: Free 5 | MonoImporter: 6 | externalObjects: {} 7 | serializedVersion: 2 8 | defaultReferences: [] 9 | executionOrder: 0 10 | icon: {instanceID: 0} 11 | userData: 12 | assetBundleName: 13 | assetBundleVariant: 14 | -------------------------------------------------------------------------------- /Editor/GraphEditor.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 6b0aaad8255a29a41b01005b4b197ba5 3 | timeCreated: 1523192854 4 | licenseType: Free 5 | MonoImporter: 6 | externalObjects: {} 7 | serializedVersion: 2 8 | defaultReferences: [] 9 | executionOrder: 0 10 | icon: {instanceID: 0} 11 | userData: 12 | assetBundleName: 13 | assetBundleVariant: 14 | -------------------------------------------------------------------------------- /EditorGUIHelper.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: e71e5af7dcf7c4949bece1e49326d2fc 3 | timeCreated: 1523706197 4 | licenseType: Free 5 | MonoImporter: 6 | externalObjects: {} 7 | serializedVersion: 2 8 | defaultReferences: [] 9 | executionOrder: 0 10 | icon: {instanceID: 0} 11 | userData: 12 | assetBundleName: 13 | assetBundleVariant: 14 | -------------------------------------------------------------------------------- /Actions/PlayTimeline.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 12cd842d723b55947a8bb2439ebadcf8 3 | timeCreated: 1523192854 4 | licenseType: Free 5 | MonoImporter: 6 | externalObjects: {} 7 | serializedVersion: 2 8 | defaultReferences: [] 9 | executionOrder: 0 10 | icon: {instanceID: 0} 11 | userData: 12 | assetBundleName: 13 | assetBundleVariant: 14 | -------------------------------------------------------------------------------- /Editor/ActionGraphEditor.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 5ee8d7350e0770d4099a14f1b57cd351 3 | timeCreated: 1523192854 4 | licenseType: Free 5 | MonoImporter: 6 | externalObjects: {} 7 | serializedVersion: 2 8 | defaultReferences: [] 9 | executionOrder: 0 10 | icon: {instanceID: 0} 11 | userData: 12 | assetBundleName: 13 | assetBundleVariant: 14 | -------------------------------------------------------------------------------- /Editor/NodeInspector.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: bc74924c4850bc949ad7f1c019968c6a 3 | timeCreated: 1523192854 4 | licenseType: Free 5 | MonoImporter: 6 | externalObjects: {} 7 | serializedVersion: 2 8 | defaultReferences: [] 9 | executionOrder: 0 10 | icon: {instanceID: 0} 11 | userData: 12 | assetBundleName: 13 | assetBundleVariant: 14 | -------------------------------------------------------------------------------- /Nodes/TransitionNode.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: f7b40c9019f0f944486f084019364b40 3 | timeCreated: 1523192854 4 | licenseType: Free 5 | MonoImporter: 6 | externalObjects: {} 7 | serializedVersion: 2 8 | defaultReferences: [] 9 | executionOrder: 0 10 | icon: {instanceID: 0} 11 | userData: 12 | assetBundleName: 13 | assetBundleVariant: 14 | -------------------------------------------------------------------------------- /UnityObjectConverter.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 750c47d8e22bb66418d2101627d72b37 3 | timeCreated: 1523192854 4 | licenseType: Free 5 | MonoImporter: 6 | externalObjects: {} 7 | serializedVersion: 2 8 | defaultReferences: [] 9 | executionOrder: 0 10 | icon: {instanceID: 0} 11 | userData: 12 | assetBundleName: 13 | assetBundleVariant: 14 | -------------------------------------------------------------------------------- /Actions/SetGameObjectActive.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 0661d15cb4ea01644ac620b5cccc36cc 3 | timeCreated: 1523709220 4 | licenseType: Free 5 | MonoImporter: 6 | externalObjects: {} 7 | serializedVersion: 2 8 | defaultReferences: [] 9 | executionOrder: 0 10 | icon: {instanceID: 0} 11 | userData: 12 | assetBundleName: 13 | assetBundleVariant: 14 | -------------------------------------------------------------------------------- /Actions/SetGameObjectsActive.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 2dcc76b2016e70147ac0ea3c1da020d3 3 | timeCreated: 1523709220 4 | licenseType: Free 5 | MonoImporter: 6 | externalObjects: {} 7 | serializedVersion: 2 8 | defaultReferences: [] 9 | executionOrder: 0 10 | icon: {instanceID: 0} 11 | userData: 12 | assetBundleName: 13 | assetBundleVariant: 14 | -------------------------------------------------------------------------------- /Editor/ActionGraphInspector.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: c4dccd43dff869848ada9c3d7d865565 3 | timeCreated: 1523192854 4 | licenseType: Free 5 | MonoImporter: 6 | externalObjects: {} 7 | serializedVersion: 2 8 | defaultReferences: [] 9 | executionOrder: 0 10 | icon: {instanceID: 0} 11 | userData: 12 | assetBundleName: 13 | assetBundleVariant: 14 | -------------------------------------------------------------------------------- /Actions/DisableAllVirtualCameras.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 8628caee1ff6cce47abed11b1e3a3889 3 | timeCreated: 1523788278 4 | licenseType: Free 5 | MonoImporter: 6 | externalObjects: {} 7 | serializedVersion: 2 8 | defaultReferences: [] 9 | executionOrder: 0 10 | icon: {instanceID: 0} 11 | userData: 12 | assetBundleName: 13 | assetBundleVariant: 14 | -------------------------------------------------------------------------------- /Actions/SetGameObjectActiveDelayed.cs.meta: -------------------------------------------------------------------------------- 1 | fileFormatVersion: 2 2 | guid: 41008e744ef89ec479c6af6a2f5f1cbb 3 | timeCreated: 1523709220 4 | licenseType: Free 5 | MonoImporter: 6 | externalObjects: {} 7 | serializedVersion: 2 8 | defaultReferences: [] 9 | executionOrder: 0 10 | icon: {instanceID: 0} 11 | userData: 12 | assetBundleName: 13 | assetBundleVariant: 14 | -------------------------------------------------------------------------------- /Nodes/TransitionNode.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | using System.Collections.Generic; 3 | using UnityEngine; 4 | 5 | namespace ActionGraph 6 | { 7 | public partial class TransitionNode : Node 8 | { 9 | // ------------------------------------------------------------------------------- 10 | 11 | public TransitionNode() 12 | { 13 | Name = "Transition Node"; 14 | } 15 | 16 | // ------------------------------------------------------------------------------- 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /Editor/GraphEditor.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | using System.Collections.Generic; 3 | using UnityEngine; 4 | using UnityEditor; 5 | 6 | namespace ActionGraph 7 | { 8 | [CustomEditor(typeof(Graph))] 9 | public class GraphEditor : Editor 10 | { 11 | public override void OnInspectorGUI() 12 | { 13 | Graph graph = (Graph)target; 14 | 15 | if (GUILayout.Button("Open Editor")) 16 | { 17 | ActionGraphEditor.CurrentGraph = graph; 18 | ActionGraphEditor.ShowEditor(); 19 | } 20 | 21 | DrawDefaultInspector(); 22 | } 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /Condition.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | using System.Collections.Generic; 3 | using UnityEngine; 4 | 5 | namespace ActionGraph 6 | { 7 | public class Condition 8 | { 9 | // ------------------------------------------------------------------------------- 10 | 11 | public virtual bool Check() 12 | { 13 | Debug.Log("Default Condition - returning true"); 14 | return true; 15 | } 16 | 17 | // ------------------------------------------------------------------------------- 18 | 19 | public virtual void OnGUI() { } 20 | 21 | // ------------------------------------------------------------------------------- 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Actions/DebugLog.cs: -------------------------------------------------------------------------------- 1 | using UnityEngine; 2 | 3 | namespace ActionGraph 4 | { 5 | public class DebugLog : Action 6 | { 7 | // ------------------------------------------------------------------------------- 8 | 9 | public string Message = ""; 10 | 11 | // ------------------------------------------------------------------------------- 12 | 13 | public override string DisplayName 14 | { 15 | get { return "Log '" + Message + "'"; } 16 | } 17 | 18 | // ------------------------------------------------------------------------------- 19 | 20 | protected override void OnStart() 21 | { 22 | Debug.Log(Message); 23 | FinishAction(); 24 | } 25 | 26 | // ------------------------------------------------------------------------------- 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /Actions/Wait.cs: -------------------------------------------------------------------------------- 1 | using UnityEngine; 2 | 3 | namespace ActionGraph 4 | { 5 | public class Wait : Action 6 | { 7 | // ------------------------------------------------------------------------------- 8 | 9 | public float Duration = 1.0f; 10 | 11 | // ------------------------------------------------------------------------------- 12 | 13 | public override string DisplayName 14 | { 15 | get { return "Wait " + Duration + " secs"; } 16 | } 17 | 18 | // ------------------------------------------------------------------------------- 19 | 20 | protected override void OnUpdate() 21 | { 22 | if (mElapsedTime >= Duration) 23 | { 24 | Status = ActionStatus.Finished; 25 | } 26 | } 27 | 28 | // ------------------------------------------------------------------------------- 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /Actions/DisableAllVirtualCameras.cs: -------------------------------------------------------------------------------- 1 | using Cinemachine; 2 | using UnityEngine; 3 | 4 | namespace ActionGraph 5 | { 6 | public class DisableAllVirtualCameras : Action 7 | { 8 | // ------------------------------------------------------------------------------ 9 | 10 | public CameraController CameraControllerTarget; 11 | public CinemachineVirtualCamera CameraToIgnore = null; 12 | 13 | // ------------------------------------------------------------------------------- 14 | 15 | protected override void OnStart() 16 | { 17 | if (CameraControllerTarget == null) 18 | { 19 | CameraControllerTarget = GameObject.FindObjectOfType(); 20 | } 21 | 22 | CameraControllerTarget.DisableAllVirtualCameras(CameraToIgnore); 23 | FinishAction(); 24 | } 25 | 26 | // ------------------------------------------------------------------------------- 27 | } 28 | } -------------------------------------------------------------------------------- /Actions/SetGameObjectsActive.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using UnityEngine; 3 | 4 | namespace ActionGraph 5 | { 6 | public class SetGameObjectsActive : Action 7 | { 8 | // ------------------------------------------------------------------------------- 9 | 10 | public List Targets; 11 | public bool Activate = true; 12 | 13 | // ------------------------------------------------------------------------------- 14 | 15 | public override string DisplayName 16 | { 17 | get { return (Activate) ? "Activate GameObjects" : "Deactivate GameObjects"; } 18 | } 19 | 20 | // ------------------------------------------------------------------------------- 21 | 22 | protected override void OnStart() 23 | { 24 | foreach (var go in Targets) 25 | { 26 | go.SetActive(Activate); 27 | } 28 | 29 | FinishAction(); 30 | } 31 | 32 | // ------------------------------------------------------------------------------- 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /Actions/SetGameObjectActive.cs: -------------------------------------------------------------------------------- 1 | using UnityEngine; 2 | 3 | namespace ActionGraph 4 | { 5 | public class SetGameObjectActive : Action 6 | { 7 | // ------------------------------------------------------------------------------- 8 | 9 | public Variable Target; 10 | public bool Activate = true; 11 | 12 | // ------------------------------------------------------------------------------- 13 | 14 | public override string DisplayName 15 | { 16 | get 17 | { 18 | var displayName = (Activate) ? "Activate " : "Deactivate "; 19 | 20 | if (Target != null) 21 | { 22 | displayName += Target.ToString(); 23 | } 24 | 25 | return displayName; 26 | } 27 | } 28 | 29 | // ------------------------------------------------------------------------------- 30 | 31 | protected override void OnStart() 32 | { 33 | if (Target != null && Target.Value != null) 34 | { 35 | Target.Value.SetActive(Activate); 36 | } 37 | 38 | FinishAction(); 39 | } 40 | 41 | // ------------------------------------------------------------------------------- 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /Actions/SetGameObjectActiveDelayed.cs: -------------------------------------------------------------------------------- 1 | using UnityEngine; 2 | 3 | namespace ActionGraph 4 | { 5 | public class SetGameObjectActiveDelayed : Action 6 | { 7 | // ------------------------------------------------------------------------------- 8 | 9 | public Variable Target; 10 | public bool Activate = true; 11 | public float Delay = 1.0f; 12 | 13 | // ------------------------------------------------------------------------------- 14 | 15 | public override string DisplayName 16 | { 17 | get 18 | { 19 | var displayName = (Activate) ? "Activate " : "Deactivate "; 20 | 21 | if (Target != null) 22 | { 23 | displayName += Target.ToString(); 24 | } 25 | 26 | return displayName; 27 | } 28 | } 29 | 30 | // ------------------------------------------------------------------------------- 31 | 32 | protected override void OnStart() 33 | { 34 | if (Target != null && Target.Value != null) 35 | { 36 | LeanTween.delayedCall(Delay, () => 37 | { 38 | Target.Value.SetActive(Activate); 39 | }); 40 | } 41 | 42 | FinishAction(); 43 | } 44 | 45 | // ------------------------------------------------------------------------------- 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /Connection.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | using System.Collections.Generic; 3 | using UnityEngine; 4 | 5 | namespace ActionGraph 6 | { 7 | public class Connection 8 | { 9 | // ------------------------------------------------------------------------------- 10 | 11 | public enum ConditionRequirements 12 | { 13 | All, 14 | Any 15 | } 16 | 17 | // ------------------------------------------------------------------------------- 18 | 19 | public ConditionRequirements ConditionRequirement; 20 | public List Conditions = new List(); 21 | public Node StartNode = null; 22 | public Node EndNode = null; 23 | 24 | // ------------------------------------------------------------------------------- 25 | 26 | public bool CheckConditions() 27 | { 28 | int numChecksPassed = 0; 29 | 30 | if (Conditions.Count > 0 ) 31 | { 32 | foreach (var condition in Conditions) 33 | { 34 | var result = condition.Check(); 35 | numChecksPassed += (result) ? 1 : 0; 36 | } 37 | } 38 | else 39 | { 40 | return true; 41 | } 42 | 43 | return (ConditionRequirement == ConditionRequirements.All && numChecksPassed == Conditions.Count) || 44 | (ConditionRequirement == ConditionRequirements.Any && numChecksPassed >= 1); 45 | 46 | } 47 | 48 | // ------------------------------------------------------------------------------- 49 | } 50 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ActionGraph 2 | A simple (work-in-progress) visual tool for crafting and structuring finite state machines in Unity in a modular way by creating states from a series of small, self-contained and re-usable actions. 3 | 4 | ## Installation 5 | 6 | Simply clone or download this repository and put everything (the ActionGraph folder) in your Unity Assets folder. That's it! 7 | 8 | ## Usage 9 | 10 | ActionGraph is still very much a work in progress and I would not currently reccomend using for anything other than a a learning resource at the moment. That being said, here's a guide to getting started: 11 | 12 | 13 | ### Creating a new Graph 14 | 15 | * Add a **Graph** component to a GameObject in your scene 16 | * Click the 'Open Editor' button or go to Window -> ActionGraph Editor to bring up the editor window 17 | * Right-click anywhere to add a node (a container for a series of actions) 18 | * The only difference between a Standard Node and a Transition Node is the latter will cause Graph.IsTransitioning to return true while it is running 19 | * Click the 'Add New Action' button to pick from any of the Actions in your project 20 | * This will bring up the ActionGraph Inspector (AGInspector) window which is similar to the standard Unity inspector but used to modify ActionGraph elements such as Actions and Conditions 21 | * Left-click and drag from one of the small white circles surrounding a node to create a connection between two nodes 22 | * Left-click the larger white circle in the middle of the connection to modify the Conditions that are required for that connection to execute 23 | 24 | ### Writing custom Actions and Conditions 25 | 26 | * Custom Actions should inherit from the Action class and can implement *OnStart*, *OnUpdate*, and *OnFinish* to execute their logic When the action has done its work it should call *FinishAction* (which is what will trigger *OnFinish* to be called) 27 | * Custom Conditions should inherit from the Condition class and need only implement *Check* which returns true or false 28 | 29 | ### Extra Notes 30 | 31 | * **WARNING:** ActionGraph doesn't always save changes automatically so be sure to use the 'Save' button in the top-left corner of the ActionGraph window regularly. 32 | * You can set which node should execute first by right-clicking a node and selecting 'Make Start Node' 33 | -------------------------------------------------------------------------------- /Actions/SetVirtualCameraActive.cs: -------------------------------------------------------------------------------- 1 | using UnityEngine; 2 | using Cinemachine; 3 | 4 | namespace ActionGraph 5 | { 6 | public class SetVirtualCameraActive : Action 7 | { 8 | // ------------------------------------------------------------------------------- 9 | 10 | public Variable Target; 11 | public bool Activate = true; 12 | public bool WaitForBlend = true; 13 | 14 | // ------------------------------------------------------------------------------- 15 | 16 | private CinemachineBrain mCinemachineBrain = null; 17 | private bool mHasStartedBlending = false; 18 | 19 | // ------------------------------------------------------------------------------- 20 | 21 | public override string DisplayName 22 | { 23 | get 24 | { 25 | var displayName = (Activate) ? "Activate " : "Deactivate "; 26 | 27 | if (Target != null) 28 | { 29 | displayName += Target.ToString(); 30 | } 31 | 32 | return displayName; 33 | } 34 | } 35 | 36 | // ------------------------------------------------------------------------------- 37 | 38 | protected override void OnStart() 39 | { 40 | if (mCinemachineBrain == null) 41 | { 42 | mCinemachineBrain = Object.FindObjectOfType(); 43 | } 44 | 45 | if (Target != null && Target.Value != null) 46 | { 47 | Target.Value.gameObject.SetActive(Activate); 48 | } 49 | 50 | if (!WaitForBlend) 51 | { 52 | FinishAction(); 53 | } 54 | 55 | mHasStartedBlending = false; 56 | } 57 | 58 | // ------------------------------------------------------------------------------- 59 | 60 | protected override void OnUpdate() 61 | { 62 | mHasStartedBlending = (mHasStartedBlending || mCinemachineBrain.IsBlending); 63 | 64 | if (WaitForBlend && mHasStartedBlending && !mCinemachineBrain.IsBlending) 65 | { 66 | FinishAction(); 67 | } 68 | } 69 | 70 | // ------------------------------------------------------------------------------- 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /Action.cs: -------------------------------------------------------------------------------- 1 | using UnityEngine; 2 | 3 | namespace ActionGraph 4 | { 5 | // ------------------------------------------------------------------------------- 6 | 7 | public enum ActionStatus 8 | { 9 | Executing, 10 | Finished 11 | } 12 | 13 | // ------------------------------------------------------------------------------- 14 | 15 | public class Action 16 | { 17 | // ------------------------------------------------------------------------------- 18 | 19 | public ActionStatus Status { get; set; } 20 | protected float mElapsedTime = 0.0f; 21 | 22 | // ------------------------------------------------------------------------------- 23 | 24 | public Action Clone() 25 | { 26 | return (Action)this.MemberwiseClone(); 27 | } 28 | 29 | // ------------------------------------------------------------------------------- 30 | 31 | public virtual string DisplayName 32 | { 33 | get { return this.GetType().Name; } 34 | } 35 | 36 | // ------------------------------------------------------------------------------- 37 | 38 | public void Start() 39 | { 40 | Status = ActionStatus.Executing; 41 | mElapsedTime = 0.0f; 42 | OnStart(); 43 | } 44 | 45 | // ------------------------------------------------------------------------------- 46 | 47 | public void Update() 48 | { 49 | OnUpdate(); 50 | mElapsedTime += Time.deltaTime; 51 | } 52 | 53 | // ------------------------------------------------------------------------------- 54 | 55 | public void Finish() 56 | { 57 | OnFinish(); 58 | } 59 | 60 | // ------------------------------------------------------------------------------- 61 | 62 | #if UNITY_EDITOR 63 | public virtual bool OnGUI() { return false; } 64 | #endif 65 | 66 | // ------------------------------------------------------------------------------- 67 | 68 | protected virtual void OnStart() { Status = ActionStatus.Executing; } 69 | protected virtual void OnUpdate() { } 70 | protected virtual void OnFinish() { } 71 | 72 | // ------------------------------------------------------------------------------- 73 | 74 | protected void FinishAction() 75 | { 76 | Status = ActionStatus.Finished; 77 | } 78 | 79 | // ------------------------------------------------------------------------------- 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /Actions/PlayTimeline.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | using System.Collections.Generic; 3 | using UnityEngine; 4 | using UnityEngine.Playables; 5 | using UnityEngine.Timeline; 6 | 7 | namespace ActionGraph 8 | { 9 | public class PlayTimeline : Action 10 | { 11 | // ------------------------------------------------------------------------------- 12 | 13 | public Variable PlayableDirector = null; 14 | public TimelineAsset TimelineOverride = null; 15 | public List TrackNames = new List(); 16 | public List TrackBindings = new List(); 17 | public bool WaitUntilComplete = true; 18 | 19 | 20 | public override string DisplayName 21 | { 22 | get 23 | { 24 | return (TimelineOverride == null) ? "Play " + PlayableDirector : "Play " + TimelineOverride.name; 25 | } 26 | } 27 | 28 | // ------------------------------------------------------------------------------- 29 | 30 | protected override void OnStart() 31 | { 32 | if (PlayableDirector.Value != null) 33 | { 34 | // Override the timeline to play, if specified 35 | if (TimelineOverride != null) 36 | { 37 | PlayableDirector.Value.playableAsset = TimelineOverride; 38 | } 39 | 40 | // Override the track bindings, if required 41 | if (TrackNames != null && TrackBindings != null) 42 | { 43 | if (TrackNames.Count == TrackBindings.Count) 44 | { 45 | for (int i = 0; i < TrackNames.Count; i++) 46 | { 47 | SetGenericBinding(TrackNames[i], TrackBindings[i]); 48 | } 49 | } 50 | else 51 | { 52 | Debug.LogError("PlayTimeline task has non-matching number of track names and bindings!"); 53 | } 54 | } 55 | 56 | // Play the timeline! 57 | PlayableDirector.Value.Play(); 58 | } 59 | 60 | if (WaitUntilComplete) 61 | { 62 | PlayableDirector.Value.stopped += OnPlayableStopped; 63 | } 64 | else 65 | { 66 | FinishAction(); 67 | } 68 | } 69 | 70 | // ------------------------------------------------------------------------------- 71 | 72 | private void OnPlayableStopped(PlayableDirector playableDirector) 73 | { 74 | PlayableDirector.Value.stopped -= OnPlayableStopped; 75 | FinishAction(); 76 | } 77 | 78 | // ------------------------------------------------------------------------------- 79 | 80 | private void SetGenericBinding(string trackName, Object trackBinding) 81 | { 82 | foreach (var playableAssetOutput in PlayableDirector.Value.playableAsset.outputs) 83 | { 84 | if (playableAssetOutput.streamName == trackName) 85 | { 86 | PlayableDirector.Value.SetGenericBinding(playableAssetOutput.sourceObject, trackBinding); 87 | } 88 | } 89 | } 90 | 91 | // ------------------------------------------------------------------------------- 92 | } 93 | } -------------------------------------------------------------------------------- /Graph.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using UnityEngine; 3 | using FullSerializer; 4 | 5 | namespace ActionGraph 6 | { 7 | public class Graph : MonoBehaviour 8 | { 9 | // ------------------------------------------------------------------------------- 10 | 11 | public string SerialisedGraph = ""; 12 | public List UnityObjectReferences = new List(); 13 | public GraphData GraphData = null; 14 | 15 | // ------------------------------------------------------------------------------- 16 | 17 | public bool IsTransitioning { get { return mCurrentNode is TransitionNode; } } 18 | public Node CurrentNode { get { return mCurrentNode; } } 19 | 20 | // ------------------------------------------------------------------------------- 21 | 22 | private fsSerializer mSerialiser = null; 23 | private Node mCurrentNode = null; 24 | 25 | // ------------------------------------------------------------------------------- 26 | 27 | public void Start() 28 | { 29 | Initialise(); 30 | Load(); 31 | 32 | if (GraphData.Nodes != null && GraphData.Nodes.Count > 0) 33 | { 34 | mCurrentNode = GraphData.Nodes[GraphData.StartNodeIndex]; 35 | mCurrentNode.OnEnter(); 36 | } 37 | else 38 | { 39 | Debug.Log("Graph doesn't have any nodes - disabling!", this); 40 | gameObject.SetActive(false); 41 | } 42 | 43 | } 44 | 45 | // ------------------------------------------------------------------------------- 46 | 47 | public void Initialise() 48 | { 49 | mSerialiser = new fsSerializer(); 50 | mSerialiser.AddConverter(new UnityObjectConverter()); 51 | mSerialiser.Context.Set(UnityObjectReferences); 52 | } 53 | 54 | // ------------------------------------------------------------------------------- 55 | 56 | public void Update() 57 | { 58 | if (mCurrentNode != null) 59 | { 60 | mCurrentNode.OnUpdate(); 61 | 62 | // Check transitions when we're ready (normally when all actions are finished, unless told otherwise) 63 | if (mCurrentNode.FinishedAllActions || !mCurrentNode.MustFinishAllActions) 64 | { 65 | var newNode = mCurrentNode.CheckConnections(); 66 | if (newNode != mCurrentNode) 67 | { 68 | mCurrentNode.OnExit(); 69 | newNode.OnEnter(); 70 | 71 | mCurrentNode = newNode; 72 | } 73 | } 74 | } 75 | } 76 | 77 | // ------------------------------------------------------------------------------- 78 | 79 | public void Save() 80 | { 81 | // We want to fill in a fresh list of references so clear the existing one 82 | // in case it contains any stale/unused references 83 | UnityObjectReferences.Clear(); 84 | 85 | // Serialise the graph and save it to a string 86 | fsData data; 87 | mSerialiser.TrySerialize(typeof(GraphData), GraphData, out data).AssertSuccessWithoutWarnings(); 88 | SerialisedGraph = fsJsonPrinter.CompressedJson(data); 89 | } 90 | 91 | // ------------------------------------------------------------------------------- 92 | 93 | public void Load() 94 | { 95 | if (GraphData == null) 96 | { 97 | if (SerialisedGraph != "") 98 | { 99 | fsData parsedData = fsJsonParser.Parse(SerialisedGraph); 100 | object deserializedGraph = null; 101 | mSerialiser.TryDeserialize(parsedData, typeof(GraphData), ref deserializedGraph).AssertSuccessWithoutWarnings(); 102 | GraphData = (GraphData)deserializedGraph; 103 | } 104 | else 105 | { 106 | GraphData = new GraphData(); 107 | } 108 | } 109 | } 110 | 111 | // ------------------------------------------------------------------------------- 112 | } 113 | } -------------------------------------------------------------------------------- /UnityObjectConverter.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using FullSerializer; 4 | 5 | namespace ActionGraph 6 | { 7 | /// 8 | /// This converter serialises a UnityObject (or subclass such as MonoBehaviour or ScriptableObject) 9 | /// as an integer index into a list maintained by a parent class which handles the *actual* serialisation. 10 | /// This allows us to leverage Unity's built-in serialisation of UnityObjects while also having our own 11 | /// serialisation logic. The external list is accessed during de/serialisation via Serializer.Context. 12 | /// This works with both scene references and asset references. 13 | /// /// 14 | public class UnityObjectConverter : fsConverter 15 | { 16 | // ------------------------------------------------------------------------------- 17 | 18 | public override bool CanProcess(Type type) 19 | { 20 | // This converter applies to any UnityEngine.Object or subclass e.g. MonoBehaviour, ScriptableObject 21 | var unityObjectType = typeof(UnityEngine.Object); 22 | return (type == unityObjectType) || (type.IsSubclassOf(unityObjectType)); 23 | } 24 | 25 | // ------------------------------------------------------------------------------- 26 | 27 | public override bool RequestCycleSupport(Type storageType) 28 | { 29 | return false; 30 | } 31 | 32 | // ------------------------------------------------------------------------------- 33 | 34 | public override bool RequestInheritanceSupport(Type storageType) 35 | { 36 | return false; 37 | } 38 | 39 | // ------------------------------------------------------------------------------- 40 | 41 | public override fsResult TrySerialize(object instance, out fsData serialized, Type storageType) 42 | { 43 | // Grab the list of serialised Unity objects from the Context object 44 | var serialisedUnityObjects = Serializer.Context.Get>(); 45 | var unityObjectInstance = instance as UnityEngine.Object; 46 | 47 | // If the Unity Object reference is null we don't need a valid index 48 | // into the list of serialisedUnityObjects, so just store -1 and return 49 | if (unityObjectInstance == null) 50 | { 51 | serialized = new fsData(-1); 52 | return fsResult.Success; 53 | } 54 | 55 | // Otherwise, search our existing list of object references for a match 56 | var serialisedUnityObjectsIndex = -1; 57 | for (var i = 0; i < serialisedUnityObjects.Count; i++) 58 | { 59 | if (serialisedUnityObjects[i] == unityObjectInstance) 60 | { 61 | serialisedUnityObjectsIndex = i; 62 | break; 63 | } 64 | } 65 | 66 | // If this is a new object reference that we don't already have in our list 67 | // add it now and serialize the new object's index in the list 68 | if (serialisedUnityObjectsIndex < 0) 69 | { 70 | serialisedUnityObjectsIndex = serialisedUnityObjects.Count; 71 | serialisedUnityObjects.Add(unityObjectInstance); 72 | } 73 | 74 | serialized = new fsData(serialisedUnityObjectsIndex); 75 | return fsResult.Success; 76 | } 77 | 78 | // ------------------------------------------------------------------------------- 79 | 80 | public override fsResult TryDeserialize(fsData data, ref object instance, Type storageType) 81 | { 82 | // Grab the list of serialised Unity objects from the Context object 83 | var serialisedUnityObjects = Serializer.Context.Get>(); 84 | var serialisedUnityObjectsIndex = (int)data.AsInt64; 85 | 86 | // Sanity check the index we've just deserialised against the Context list 87 | if (serialisedUnityObjectsIndex < 0 || serialisedUnityObjectsIndex >= serialisedUnityObjects.Count) 88 | { 89 | return fsResult.Warn("Invalid Unity Object reference index, could not deserialise!"); 90 | } 91 | 92 | instance = serialisedUnityObjects[serialisedUnityObjectsIndex]; 93 | return fsResult.Success; 94 | } 95 | 96 | // ------------------------------------------------------------------------------- 97 | 98 | public override object CreateInstance(fsData data, Type storageType) 99 | { 100 | // We never want the serialiser to create Unity objects, null references are fine! 101 | return null; 102 | } 103 | 104 | // ------------------------------------------------------------------------------- 105 | } 106 | } -------------------------------------------------------------------------------- /Editor/NodeInspector.cs: -------------------------------------------------------------------------------- 1 | using System.Collections; 2 | using System.Collections.Generic; 3 | using UnityEngine; 4 | using UnityEditor; 5 | using System; 6 | using System.Reflection; 7 | using System.Linq; 8 | 9 | namespace ActionGraph 10 | { 11 | public static class NodeInspector 12 | { 13 | // ------------------------------------------------------------------------------- 14 | 15 | public static void OnGUI(this Node node) 16 | { 17 | node.Name = EditorGUILayout.TextField("Name", node.Name); 18 | node.MustFinishAllActions = EditorGUILayout.Toggle("Must Finish All Actions?", node.MustFinishAllActions); 19 | 20 | EditorGUILayout.LabelField("ACTIONS", EditorStyles.boldLabel); 21 | 22 | if (GUILayout.Button("Add New Action")) 23 | { 24 | // Get a list of all possible Actions via reflection 25 | Type baseActionType = typeof(Action); 26 | Assembly assembly = Assembly.GetAssembly(baseActionType); 27 | List allActionTypes = assembly.GetTypes().Where(type => type != baseActionType && baseActionType.IsAssignableFrom(type)).ToList(); 28 | 29 | // Create a menu item for each type so we can create new instances from the GUI 30 | var menu = new GenericMenu(); 31 | 32 | // Also, if we have an action copied to the clipboard, add an option to paste that in instead 33 | if (ActionGraphEditor.CopiedAction != null) 34 | { 35 | menu.AddItem(new GUIContent("PASTE COPIED ACTION"), false, () => 36 | { 37 | var newAction = ActionGraphEditor.CopiedAction.Clone(); 38 | node.Actions.Add(newAction); 39 | ShowActionGraphInspector(newAction); 40 | }); 41 | } 42 | 43 | foreach (var actionType in allActionTypes) 44 | { 45 | menu.AddItem(new GUIContent(actionType.Name), false, () => 46 | { 47 | var newAction = Activator.CreateInstance(actionType) as Action; 48 | node.Actions.Add(newAction); 49 | ShowActionGraphInspector(newAction); 50 | }); 51 | } 52 | menu.ShowAsContext(); 53 | } 54 | 55 | Action actionToMoveUp = null; 56 | Action actionToMoveDown = null; 57 | 58 | foreach (var action in node.Actions) 59 | { 60 | var labelStyle = EditorStyles.label; 61 | 62 | // Highlight the currently executing action, if applicable 63 | if ((ActionGraphEditor.CurrentGraph.CurrentNode != null && 64 | ActionGraphEditor.CurrentGraph.CurrentNode.CurrentAction == action)) 65 | { 66 | labelStyle = EditorStyles.boldLabel; 67 | } 68 | 69 | EditorGUILayout.BeginHorizontal(); 70 | EditorGUILayout.LabelField(action.DisplayName, labelStyle); 71 | 72 | if (GUILayout.Button("↑")) 73 | { 74 | actionToMoveUp = action; 75 | } 76 | 77 | if (GUILayout.Button("↓")) 78 | { 79 | actionToMoveDown = action; 80 | } 81 | 82 | if (GUILayout.Button("Edit")) 83 | { 84 | ActionGraphEditor.MarkAsDirty(); 85 | ShowActionGraphInspector(action); 86 | } 87 | 88 | if (GUILayout.Button("Delete")) 89 | { 90 | node.Actions.Remove(action); 91 | ActionGraphInspector.Clear(); 92 | break; 93 | } 94 | 95 | EditorGUILayout.EndHorizontal(); 96 | EditorGUILayout.Space(); 97 | } 98 | 99 | // Re-order actions list if requested! 100 | if (actionToMoveUp != null) 101 | { 102 | var actionIndex = node.Actions.IndexOf(actionToMoveUp); 103 | if (actionIndex > 0) 104 | { 105 | node.Actions.Swap(actionIndex, actionIndex-1); 106 | } 107 | } 108 | else if (actionToMoveDown != null) 109 | { 110 | var actionIndex = node.Actions.IndexOf(actionToMoveDown); 111 | if (actionIndex < node.Actions.Count - 1) 112 | { 113 | node.Actions.Swap(actionIndex, actionIndex+1); 114 | } 115 | } 116 | 117 | EditorGUILayout.Space(); 118 | } 119 | 120 | // ------------------------------------------------------------------------------- 121 | 122 | private static void ShowActionGraphInspector(Action action) 123 | { 124 | ActionGraphInspector.CurrentGraph = ActionGraphEditor.CurrentGraph; 125 | ActionGraphInspector.SetCurrentAction(action); 126 | ActionGraphInspector.ShowEditor(); 127 | } 128 | 129 | // ------------------------------------------------------------------------------- 130 | } 131 | } 132 | -------------------------------------------------------------------------------- /Variable.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Reflection; 3 | using UnityEngine; 4 | 5 | namespace ActionGraph 6 | { 7 | /// 8 | /// Can hold a value directly or be bound to a property/field on a MonoBehaviour. 9 | /// 10 | /// Variable type 11 | public class Variable 12 | { 13 | // ------------------------------------------------------------------------------- 14 | 15 | [SerializeField] private T mValue; 16 | [SerializeField] private string mBoundMemberName = null; 17 | [SerializeField] private MonoBehaviour mBoundOwner = null; 18 | [SerializeField] private Type mBoundOwnerType = null; 19 | 20 | // ------------------------------------------------------------------------------- 21 | 22 | public T Value 23 | { 24 | get 25 | { 26 | if (mBoundMemberName != null && mBoundOwner != null) 27 | { 28 | var property = mBoundOwnerType.GetProperty(mBoundMemberName); 29 | if (property != null && property.CanRead) 30 | { 31 | return getValue(property.GetGetMethod().Invoke(mBoundOwner, null)); 32 | } 33 | else 34 | { 35 | var field = mBoundOwnerType.GetField(mBoundMemberName); 36 | if (field != null) 37 | { 38 | return getValue(field.GetValue(mBoundOwner)); 39 | } 40 | else 41 | { 42 | Debug.LogError("Failed to retreive either Property or Field for bound Variable with member name: " + mBoundMemberName); 43 | return mValue; 44 | } 45 | } 46 | } 47 | else 48 | { 49 | return mValue; 50 | } 51 | } 52 | set 53 | { 54 | if (mBoundMemberName != null) 55 | { 56 | var property = mBoundOwnerType.GetProperty(mBoundMemberName); 57 | if (property != null && property.CanWrite) 58 | { 59 | property.GetSetMethod().Invoke(mBoundOwner, new object[] { value }); 60 | } 61 | else 62 | { 63 | var field = mBoundOwnerType.GetField(mBoundMemberName); 64 | if (field != null) 65 | { 66 | field.SetValue(mBoundOwner, value); 67 | } 68 | else 69 | { 70 | Debug.LogError("Failed to retreive either Property or Field for bound Variable with member name: " + mBoundMemberName); 71 | } 72 | } 73 | } 74 | else 75 | { 76 | mValue = value; 77 | } 78 | } 79 | } 80 | 81 | // ------------------------------------------------------------------------------- 82 | 83 | public void Bind(MemberInfo member, MonoBehaviour owner) 84 | { 85 | if (member is FieldInfo || member is PropertyInfo) 86 | { 87 | mBoundOwner = owner; 88 | mBoundMemberName = member.Name; 89 | mBoundOwnerType = owner.GetType(); 90 | } 91 | } 92 | 93 | // ------------------------------------------------------------------------------- 94 | 95 | public void Unbind() 96 | { 97 | mBoundOwner = null; 98 | mBoundMemberName = null; 99 | mBoundOwnerType = null; 100 | } 101 | 102 | // ------------------------------------------------------------------------------- 103 | 104 | public override string ToString() 105 | { 106 | if (mValue != null) 107 | { 108 | var valueAsUnityObject = (mValue as UnityEngine.Object); 109 | return (valueAsUnityObject != null) ? valueAsUnityObject.name : mValue.ToString(); 110 | } 111 | else if (mBoundMemberName != null) 112 | { 113 | return mBoundOwner.name + "." + mBoundMemberName; 114 | } 115 | 116 | return "NULL"; 117 | } 118 | 119 | // ------------------------------------------------------------------------------- 120 | 121 | private T getValue(object value) 122 | { 123 | // Are we bound to a MonoBehaviour but actually want to return the GameObject it belongs to? 124 | if (typeof(T) == typeof(GameObject) && typeof(MonoBehaviour).IsAssignableFrom(value.GetType())) 125 | { 126 | return (T)((value as MonoBehaviour).gameObject as object); 127 | } 128 | 129 | // Otherwise just return the input value directly 130 | return (T)value; 131 | } 132 | 133 | // ------------------------------------------------------------------------------- 134 | } 135 | } -------------------------------------------------------------------------------- /Node.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using UnityEngine; 3 | 4 | namespace ActionGraph 5 | { 6 | public partial class Node 7 | { 8 | // ------------------------------------------------------------------------------- 9 | 10 | public string Name = "Node"; 11 | public Rect GraphWindowRect = new Rect(10, 10, 300, 75); 12 | public bool MustFinishAllActions = true; 13 | public List Actions = new List(); 14 | public List OutgoingConnections = new List(); 15 | public List IncomingConnections = new List(); 16 | private int mCurrentActionIndex = 0; 17 | 18 | #if UNITY_EDITOR 19 | public class ConnectionHandle 20 | { 21 | public Vector2 Position; 22 | public Rect DisplayRect; 23 | } 24 | 25 | [System.NonSerialized] 26 | public List ConnectionHandles = new List(); 27 | #endif 28 | 29 | // ------------------------------------------------------------------------------- 30 | 31 | public bool FinishedAllActions { get; set; } 32 | public Action CurrentAction { get { return (mCurrentActionIndex < Actions.Count) ? Actions[mCurrentActionIndex] : null; } } 33 | 34 | // ------------------------------------------------------------------------------- 35 | 36 | public virtual void OnEnter() 37 | { 38 | mCurrentActionIndex = 0; 39 | 40 | if (Actions.Count > 0) 41 | { 42 | FinishedAllActions = false; 43 | Actions[mCurrentActionIndex].Start(); 44 | } 45 | else 46 | { 47 | FinishedAllActions = true; 48 | } 49 | } 50 | 51 | // ------------------------------------------------------------------------------- 52 | 53 | public virtual void OnUpdate() 54 | { 55 | if (FinishedAllActions || mCurrentActionIndex >= Actions.Count) 56 | { 57 | return; 58 | } 59 | 60 | // Update the current action until it says it's done 61 | var currentAction = Actions[mCurrentActionIndex]; 62 | currentAction.Update(); 63 | var actionComplete = (currentAction.Status == ActionStatus.Finished); // KB TODO: SUPPORT THIS ON START TOO 64 | 65 | if (actionComplete) 66 | { 67 | currentAction.Finish(); 68 | mCurrentActionIndex++; 69 | 70 | // Have we finished running all of our actions? 71 | if (mCurrentActionIndex >= Actions.Count) 72 | { 73 | FinishedAllActions = true; 74 | } 75 | else 76 | { 77 | Actions[mCurrentActionIndex].Start(); 78 | } 79 | } 80 | } 81 | 82 | // ------------------------------------------------------------------------------- 83 | 84 | public virtual void OnExit() 85 | { 86 | // If we're leaving this node before we've finished every action, make sure we 87 | // give our current action the chance to clean up after itself! 88 | if (!FinishedAllActions && mCurrentActionIndex < Actions.Count) 89 | { 90 | Actions[mCurrentActionIndex].Finish(); 91 | } 92 | } 93 | 94 | // ------------------------------------------------------------------------------- 95 | 96 | public virtual void OnDelete() 97 | { 98 | // Make sure we clean up any connection we have to other nodes! 99 | foreach (var incomingConnection in IncomingConnections) 100 | { 101 | incomingConnection.StartNode.OutgoingConnections.Remove(incomingConnection); 102 | } 103 | foreach (var outgoingConnection in OutgoingConnections) 104 | { 105 | outgoingConnection.EndNode.IncomingConnections.Remove(outgoingConnection); 106 | } 107 | } 108 | 109 | // ------------------------------------------------------------------------------- 110 | 111 | public Connection GetOutgoingConnectionToNode(Node node) 112 | { 113 | foreach (var connection in OutgoingConnections) 114 | { 115 | if (connection.EndNode == node) 116 | { 117 | return connection; 118 | } 119 | } 120 | 121 | return null; 122 | } 123 | 124 | // ------------------------------------------------------------------------------- 125 | 126 | public virtual Node CheckConnections() 127 | { 128 | // Check all of our outgoing connections 129 | foreach (var outgoingConnection in OutgoingConnections) 130 | { 131 | // If we pass all the necessary conditions, return the EndNode for a transition! 132 | if (outgoingConnection.CheckConditions()) 133 | { 134 | return outgoingConnection.EndNode; 135 | } 136 | } 137 | 138 | return this; 139 | } 140 | 141 | // ------------------------------------------------------------------------------- 142 | } 143 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | CC0 1.0 Universal 2 | 3 | Statement of Purpose 4 | 5 | The laws of most jurisdictions throughout the world automatically confer 6 | exclusive Copyright and Related Rights (defined below) upon the creator and 7 | subsequent owner(s) (each and all, an "owner") of an original work of 8 | authorship and/or a database (each, a "Work"). 9 | 10 | Certain owners wish to permanently relinquish those rights to a Work for the 11 | purpose of contributing to a commons of creative, cultural and scientific 12 | works ("Commons") that the public can reliably and without fear of later 13 | claims of infringement build upon, modify, incorporate in other works, reuse 14 | and redistribute as freely as possible in any form whatsoever and for any 15 | purposes, including without limitation commercial purposes. These owners may 16 | contribute to the Commons to promote the ideal of a free culture and the 17 | further production of creative, cultural and scientific works, or to gain 18 | reputation or greater distribution for their Work in part through the use and 19 | efforts of others. 20 | 21 | For these and/or other purposes and motivations, and without any expectation 22 | of additional consideration or compensation, the person associating CC0 with a 23 | Work (the "Affirmer"), to the extent that he or she is an owner of Copyright 24 | and Related Rights in the Work, voluntarily elects to apply CC0 to the Work 25 | and publicly distribute the Work under its terms, with knowledge of his or her 26 | Copyright and Related Rights in the Work and the meaning and intended legal 27 | effect of CC0 on those rights. 28 | 29 | 1. Copyright and Related Rights. A Work made available under CC0 may be 30 | protected by copyright and related or neighboring rights ("Copyright and 31 | Related Rights"). Copyright and Related Rights include, but are not limited 32 | to, the following: 33 | 34 | i. the right to reproduce, adapt, distribute, perform, display, communicate, 35 | and translate a Work; 36 | 37 | ii. moral rights retained by the original author(s) and/or performer(s); 38 | 39 | iii. publicity and privacy rights pertaining to a person's image or likeness 40 | depicted in a Work; 41 | 42 | iv. rights protecting against unfair competition in regards to a Work, 43 | subject to the limitations in paragraph 4(a), below; 44 | 45 | v. rights protecting the extraction, dissemination, use and reuse of data in 46 | a Work; 47 | 48 | vi. database rights (such as those arising under Directive 96/9/EC of the 49 | European Parliament and of the Council of 11 March 1996 on the legal 50 | protection of databases, and under any national implementation thereof, 51 | including any amended or successor version of such directive); and 52 | 53 | vii. other similar, equivalent or corresponding rights throughout the world 54 | based on applicable law or treaty, and any national implementations thereof. 55 | 56 | 2. Waiver. To the greatest extent permitted by, but not in contravention of, 57 | applicable law, Affirmer hereby overtly, fully, permanently, irrevocably and 58 | unconditionally waives, abandons, and surrenders all of Affirmer's Copyright 59 | and Related Rights and associated claims and causes of action, whether now 60 | known or unknown (including existing as well as future claims and causes of 61 | action), in the Work (i) in all territories worldwide, (ii) for the maximum 62 | duration provided by applicable law or treaty (including future time 63 | extensions), (iii) in any current or future medium and for any number of 64 | copies, and (iv) for any purpose whatsoever, including without limitation 65 | commercial, advertising or promotional purposes (the "Waiver"). Affirmer makes 66 | the Waiver for the benefit of each member of the public at large and to the 67 | detriment of Affirmer's heirs and successors, fully intending that such Waiver 68 | shall not be subject to revocation, rescission, cancellation, termination, or 69 | any other legal or equitable action to disrupt the quiet enjoyment of the Work 70 | by the public as contemplated by Affirmer's express Statement of Purpose. 71 | 72 | 3. Public License Fallback. Should any part of the Waiver for any reason be 73 | judged legally invalid or ineffective under applicable law, then the Waiver 74 | shall be preserved to the maximum extent permitted taking into account 75 | Affirmer's express Statement of Purpose. In addition, to the extent the Waiver 76 | is so judged Affirmer hereby grants to each affected person a royalty-free, 77 | non transferable, non sublicensable, non exclusive, irrevocable and 78 | unconditional license to exercise Affirmer's Copyright and Related Rights in 79 | the Work (i) in all territories worldwide, (ii) for the maximum duration 80 | provided by applicable law or treaty (including future time extensions), (iii) 81 | in any current or future medium and for any number of copies, and (iv) for any 82 | purpose whatsoever, including without limitation commercial, advertising or 83 | promotional purposes (the "License"). The License shall be deemed effective as 84 | of the date CC0 was applied by Affirmer to the Work. Should any part of the 85 | License for any reason be judged legally invalid or ineffective under 86 | applicable law, such partial invalidity or ineffectiveness shall not 87 | invalidate the remainder of the License, and in such case Affirmer hereby 88 | affirms that he or she will not (i) exercise any of his or her remaining 89 | Copyright and Related Rights in the Work or (ii) assert any associated claims 90 | and causes of action with respect to the Work, in either case contrary to 91 | Affirmer's express Statement of Purpose. 92 | 93 | 4. Limitations and Disclaimers. 94 | 95 | a. No trademark or patent rights held by Affirmer are waived, abandoned, 96 | surrendered, licensed or otherwise affected by this document. 97 | 98 | b. Affirmer offers the Work as-is and makes no representations or warranties 99 | of any kind concerning the Work, express, implied, statutory or otherwise, 100 | including without limitation warranties of title, merchantability, fitness 101 | for a particular purpose, non infringement, or the absence of latent or 102 | other defects, accuracy, or the present or absence of errors, whether or not 103 | discoverable, all to the greatest extent permissible under applicable law. 104 | 105 | c. Affirmer disclaims responsibility for clearing rights of other persons 106 | that may apply to the Work or any use thereof, including without limitation 107 | any person's Copyright and Related Rights in the Work. Further, Affirmer 108 | disclaims responsibility for obtaining any necessary consents, permissions 109 | or other rights required for any use of the Work. 110 | 111 | d. Affirmer understands and acknowledges that Creative Commons is not a 112 | party to this document and has no duty or obligation with respect to this 113 | CC0 or use of the Work. 114 | 115 | For more information, please see 116 | 117 | -------------------------------------------------------------------------------- /Editor/ActionGraphInspector.cs: -------------------------------------------------------------------------------- 1 | using UnityEngine; 2 | using UnityEditor; 3 | using System.Reflection; 4 | using System.Collections.Generic; 5 | using UnityEngine.SceneManagement; 6 | using System; 7 | using System.Linq; 8 | 9 | namespace ActionGraph 10 | { 11 | public class ActionGraphInspector : EditorWindow 12 | { 13 | // ------------------------------------------------------------------------------- 14 | 15 | public static Graph CurrentGraph = null; 16 | public static ActionGraphInspector Instance = null; 17 | 18 | private static Action mCurrentAction = null; 19 | private static Connection mCurrentConnection = null; 20 | 21 | // ------------------------------------------------------------------------------- 22 | 23 | [MenuItem("Window/ActionGraph Inspector")] 24 | public static void ShowEditor() 25 | { 26 | Instance = EditorWindow.GetWindow(); 27 | Instance.Init(); 28 | } 29 | 30 | // ------------------------------------------------------------------------------- 31 | 32 | public static void Clear() 33 | { 34 | if (Instance != null) 35 | { 36 | CurrentGraph = null; 37 | mCurrentAction = null; 38 | mCurrentConnection = null; 39 | Instance.Repaint(); 40 | } 41 | } 42 | 43 | // ------------------------------------------------------------------------------- 44 | 45 | public static void SetCurrentAction(Action newCurrentAction) 46 | { 47 | mCurrentAction = newCurrentAction; 48 | mCurrentConnection = null; 49 | } 50 | 51 | // ------------------------------------------------------------------------------- 52 | 53 | public static void SetCurrentConnection(Connection newCurrentConnection) 54 | { 55 | mCurrentAction = null; 56 | mCurrentConnection = newCurrentConnection; 57 | } 58 | 59 | // ------------------------------------------------------------------------------- 60 | 61 | void Init() 62 | { 63 | titleContent = new GUIContent("AG Inspector"); 64 | } 65 | 66 | // ------------------------------------------------------------------------------- 67 | 68 | void OnGUI() 69 | { 70 | if (mCurrentAction != null) 71 | { 72 | ShowActionInspector(); 73 | } 74 | else if (mCurrentConnection != null) 75 | { 76 | ShowConnectionInspector(mCurrentConnection); 77 | 78 | // Do we have a two-way connection between these two nodes? 79 | var otherConnection = mCurrentConnection.EndNode.GetOutgoingConnectionToNode(mCurrentConnection.StartNode); 80 | if (otherConnection != null) 81 | { 82 | // If so, draw the *other* conneciton as well 83 | EditorGUILayout.Space(); 84 | EditorGUILayout.LabelField("", GUI.skin.horizontalSlider); 85 | EditorGUILayout.Space(); 86 | 87 | ShowConnectionInspector(otherConnection); 88 | } 89 | } 90 | else 91 | { 92 | EditorGUILayout.Space(); 93 | EditorGUILayout.LabelField("No Action or Connection selected from the ActionGraph Editor!"); 94 | EditorGUILayout.Space(); 95 | } 96 | 97 | // Make sure the main editor window shows up-to-date changes we make 98 | ActionGraphEditor.MarkAsDirty(true); 99 | } 100 | 101 | // ------------------------------------------------------------------------------- 102 | 103 | void ShowActionInspector() 104 | { 105 | EditorGUILayout.Space(); 106 | EditorGUILayout.LabelField(mCurrentAction.GetType().Name, EditorStyles.boldLabel); 107 | EditorGUILayout.Space(); 108 | 109 | // Actions can control their own GUI, or we can just do a generic version ourselves 110 | if (!mCurrentAction.OnGUI()) 111 | { 112 | // Show inspector GUI for all public fields on the CurrentAction 113 | foreach (FieldInfo fieldInfo in mCurrentAction.GetType().GetFields()) 114 | { 115 | if (fieldInfo != null && !fieldInfo.IsStatic) 116 | { 117 | var value = fieldInfo.GetValue(mCurrentAction); 118 | value = EditorGUIHelper.ShowInspectorForType(fieldInfo.FieldType, value, fieldInfo.Name); 119 | fieldInfo.SetValue(mCurrentAction, value); 120 | } 121 | } 122 | } 123 | 124 | if (GUILayout.Button("Copy Action")) 125 | { 126 | ActionGraphEditor.CopiedAction = mCurrentAction.Clone(); 127 | } 128 | } 129 | 130 | // ------------------------------------------------------------------------------- 131 | 132 | void ShowConnectionInspector(Connection connection) 133 | { 134 | EditorGUILayout.Space(); 135 | EditorGUILayout.LabelField(connection.StartNode.Name + " -> " + connection.EndNode.Name, EditorStyles.boldLabel); 136 | 137 | EditorGUILayout.Space(); 138 | connection.ConditionRequirement = (Connection.ConditionRequirements)EditorGUILayout.EnumPopup("Condition Requirements", connection.ConditionRequirement); 139 | EditorGUILayout.Space(); 140 | 141 | EditorGUIHelper.CreateConditionButton((condition) => 142 | { 143 | connection.Conditions.Add(condition as Condition); 144 | }); 145 | 146 | EditorGUILayout.Space(); 147 | EditorGUILayout.LabelField("CONDITIONS", EditorStyles.boldLabel); 148 | 149 | if (connection.Conditions == null || connection.Conditions.Count == 0) 150 | { 151 | EditorGUILayout.LabelField("None! This connection will transition automatically."); 152 | } 153 | else 154 | { 155 | Condition conditionToDelete = null; 156 | foreach (var condition in connection.Conditions) 157 | { 158 | EditorGUILayout.Space(); 159 | 160 | EditorGUILayout.BeginHorizontal(); 161 | EditorGUILayout.LabelField(condition.ToString(), EditorStyles.boldLabel); 162 | if (GUILayout.Button("Delete")) 163 | { 164 | conditionToDelete = condition; 165 | break; 166 | } 167 | EditorGUILayout.EndHorizontal(); 168 | 169 | // Show inspector GUI for all public fields on the Condition 170 | EditorGUIHelper.ShowConditionInspector(condition); 171 | } 172 | 173 | if (conditionToDelete != null) 174 | { 175 | connection.Conditions.Remove(conditionToDelete); 176 | conditionToDelete = null; 177 | } 178 | } 179 | 180 | EditorGUILayout.Space(); 181 | 182 | if (GUILayout.Button("*DELETE CONNECTION*")) 183 | { 184 | connection.StartNode.OutgoingConnections.Remove(connection); 185 | connection.EndNode.IncomingConnections.Remove(connection); 186 | if (connection == mCurrentConnection) 187 | { 188 | mCurrentConnection = null; 189 | } 190 | return; 191 | } 192 | } 193 | 194 | // ------------------------------------------------------------------------------- 195 | } 196 | } 197 | -------------------------------------------------------------------------------- /EditorGUIHelper.cs: -------------------------------------------------------------------------------- 1 | #if UNITY_EDITOR 2 | 3 | using System; 4 | using System.Collections.Generic; 5 | using UnityEngine; 6 | using UnityEditor; 7 | using System.Linq; 8 | using System.Reflection; 9 | using UnityEngine.SceneManagement; 10 | 11 | namespace ActionGraph 12 | { 13 | public static class EditorGUIHelper 14 | { 15 | // ------------------------------------------------------------------------------- 16 | 17 | public static object ShowInspectorForType(System.Type type, object value, string name) 18 | { 19 | if (type == typeof(bool)) 20 | { 21 | return EditorGUILayout.Toggle(name, (bool)value); 22 | } 23 | else if (type == typeof(string)) 24 | { 25 | return EditorGUILayout.TextField(name, (string)value); 26 | } 27 | else if (type == typeof(int)) 28 | { 29 | return EditorGUILayout.IntField(name, (int)value); 30 | } 31 | else if (type == typeof(float)) 32 | { 33 | return EditorGUILayout.FloatField(name, (float)value); 34 | } 35 | else if (type == typeof(Vector2)) 36 | { 37 | return EditorGUILayout.Vector2Field(name, (Vector2)value); 38 | } 39 | else if (type == typeof(Vector3)) 40 | { 41 | return EditorGUILayout.Vector3Field(name, (Vector3)value); 42 | } 43 | else if (typeof(Enum).IsAssignableFrom(type)) 44 | { 45 | return EditorGUILayout.EnumPopup(name, (Enum)value); 46 | } 47 | else if (typeof(IList<>).IsAssignableFrom(type)) 48 | { 49 | EditorGUILayout.LabelField("TODO: LIST SUPPORT"); 50 | } 51 | else if (typeof(UnityEngine.Object).IsAssignableFrom(type)) 52 | { 53 | return EditorGUILayout.ObjectField(name, (UnityEngine.Object)value, type, 54 | typeof(Component).IsAssignableFrom(type) || type == typeof(GameObject) || type == typeof(UnityEngine.Object)); 55 | } 56 | else if (type.IsGenericType && typeof(Variable<>).IsAssignableFrom(type.GetGenericTypeDefinition())) 57 | { 58 | EditorGUILayout.BeginHorizontal(); 59 | 60 | if (value == null) 61 | { 62 | value = System.Activator.CreateInstance(type); 63 | } 64 | 65 | var variableBoundMemberNameField = GetPrivateFieldInfo(value, "mBoundMemberName"); 66 | var variableBoundMemberName = (string)variableBoundMemberNameField.GetValue(value); 67 | 68 | bool isBound = (variableBoundMemberName != null); 69 | if (!isBound) 70 | { 71 | var variableValueField = GetPrivateFieldInfo(value, "mValue"); 72 | var variableValue = variableValueField.GetValue(value); 73 | var variableValuetype = variableValueField.FieldType; 74 | 75 | variableValueField.SetValue(value, ShowInspectorForType(variableValuetype, variableValue, name)); 76 | } 77 | else 78 | { 79 | var variableBoundOwnerField = GetPrivateFieldInfo(value, "mBoundOwner"); 80 | var variableBoundOwnerValue = (MonoBehaviour)variableBoundOwnerField.GetValue(value); 81 | 82 | if (variableBoundOwnerValue != null) 83 | { 84 | string path = GetComponentPath(variableBoundOwnerValue); 85 | EditorGUILayout.LabelField(name + ": " + path + "/" + variableBoundMemberName); 86 | } 87 | else 88 | { 89 | Debug.LogWarning("Bound value couldn't be found, the object may have been deleted? Unbinding..."); 90 | UnbindVariable(value); 91 | } 92 | } 93 | 94 | if (GUILayout.Button("@", GUILayout.Width(20), GUILayout.Height(16))) 95 | { 96 | var menu = new GenericMenu(); 97 | if (isBound) 98 | { 99 | menu.AddItem(new GUIContent("Unbind"), false, () => { UnbindVariable(value); }); 100 | } 101 | else 102 | { 103 | // Grab a list of all the GameObjects at the root of the scene 104 | List sceneGameObjects = new List(); 105 | SceneManager.GetActiveScene().GetRootGameObjects(sceneGameObjects); 106 | 107 | var genericVariableType = type.GetGenericArguments()[0]; 108 | 109 | // Iterate over all the GameObjects at the root of the scene 110 | foreach (var gameObject in sceneGameObjects) 111 | { 112 | // For each scene object, iterate over all components (and children's components) 113 | // and look for any properties or fields that match our Variable's generic type 114 | foreach (var component in gameObject.GetComponentsInChildren()) 115 | { 116 | // GameObjects are special type because we can get at them from components.. 117 | var showComponentsForGameObjects = (genericVariableType == typeof(GameObject)); 118 | 119 | foreach (PropertyInfo componentPropertyInfo in component.GetType().GetProperties()) 120 | { 121 | var propertyType = componentPropertyInfo.PropertyType; 122 | 123 | // Do we actually want to bind to the gameObject property on a component, rather than the component itself? 124 | var bindGameObjectFromMonoBehaviour = (showComponentsForGameObjects && typeof(MonoBehaviour).IsAssignableFrom(propertyType)); 125 | 126 | if (bindGameObjectFromMonoBehaviour || propertyType == genericVariableType || genericVariableType.IsAssignableFrom(propertyType)) 127 | { 128 | var menuPath = "Properties/" + GetComponentPath(component) + "/" + componentPropertyInfo.Name; 129 | menu.AddItem(new GUIContent(menuPath), false, () => 130 | { 131 | BindVariable(value, component, componentPropertyInfo); 132 | }); 133 | } 134 | } 135 | 136 | foreach (FieldInfo componentFieldInfo in component.GetType().GetFields()) 137 | { 138 | var fieldType = componentFieldInfo.FieldType; 139 | var bindGameObjectFromComponent = (showComponentsForGameObjects && typeof(MonoBehaviour).IsAssignableFrom(fieldType)); 140 | 141 | if (bindGameObjectFromComponent || fieldType == genericVariableType || genericVariableType.IsAssignableFrom(fieldType)) 142 | { 143 | var menuPath = "Fields/" + GetComponentPath(component) + "/" + componentFieldInfo.Name; 144 | menu.AddItem(new GUIContent(menuPath), false, () => 145 | { 146 | MemberInfo memberToBind = componentFieldInfo; 147 | 148 | // Do we actually want to bind to the gameObject property on a component, rather than the component itself? 149 | if (bindGameObjectFromComponent) 150 | { 151 | memberToBind = component.GetType().GetProperty("gameObject"); 152 | } 153 | 154 | BindVariable(value, component, memberToBind); 155 | }); 156 | } 157 | } 158 | } 159 | } 160 | } 161 | menu.ShowAsContext(); 162 | } 163 | 164 | EditorGUILayout.EndHorizontal(); 165 | } 166 | else 167 | { 168 | EditorGUILayout.LabelField("Couldn't display inspector for '" + name + "' of type: " + type.ToString()); 169 | } 170 | 171 | return value; 172 | } 173 | 174 | // ------------------------------------------------------------------------------- 175 | 176 | public static string GetComponentPath(Component component) 177 | { 178 | Transform transform = component.transform; 179 | string path = transform.name; 180 | 181 | while (transform.parent != null) 182 | { 183 | transform = transform.parent; 184 | path = transform.name + "/" + path; 185 | } 186 | 187 | return path; 188 | } 189 | 190 | // ------------------------------------------------------------------------------- 191 | 192 | public static FieldInfo GetPrivateFieldInfo(object owner, string fieldName) 193 | { 194 | return owner.GetType().GetField(fieldName, BindingFlags.NonPublic | BindingFlags.Instance); 195 | } 196 | 197 | // ------------------------------------------------------------------------------- 198 | 199 | public static void CreateConditionButton(Action callback, string buttonText = "Add Condition") 200 | { 201 | Condition newCondition = null; 202 | 203 | if (GUILayout.Button(buttonText)) 204 | { 205 | // Get a list of all possible Conditions via reflection 206 | Type baseConditionType = typeof(Condition); 207 | Assembly assembly = Assembly.GetAssembly(baseConditionType); 208 | List allConditionTypes = assembly.GetTypes().Where(type => type != baseConditionType && baseConditionType.IsAssignableFrom(type)).ToList(); 209 | 210 | // Create a menu item for each type so we can create new instances from the GUI 211 | var menu = new GenericMenu(); 212 | foreach (var conditionType in allConditionTypes) 213 | { 214 | menu.AddItem(new GUIContent(conditionType.Name), false, () => 215 | { 216 | newCondition = (Activator.CreateInstance(conditionType) as Condition); 217 | callback(newCondition as Condition); 218 | }); 219 | } 220 | menu.ShowAsContext(); 221 | } 222 | } 223 | 224 | // ------------------------------------------------------------------------------- 225 | 226 | public static void ShowConditionInspector(Condition condition) 227 | { 228 | // Show inspector GUI for all public fields on the Condition 229 | foreach (FieldInfo fieldInfo in condition.GetType().GetFields()) 230 | { 231 | if (fieldInfo != null && !fieldInfo.IsStatic) 232 | { 233 | var value = fieldInfo.GetValue(condition); 234 | value = ShowInspectorForType(fieldInfo.FieldType, value, fieldInfo.Name); 235 | fieldInfo.SetValue(condition, value); 236 | } 237 | } 238 | } 239 | 240 | // ------------------------------------------------------------------------------- 241 | 242 | private static void BindVariable(object variableObject, Component owner, MemberInfo memberInfo) 243 | { 244 | var variableBoundMemberNameField = GetPrivateFieldInfo(variableObject, "mBoundMemberName"); 245 | var variableBoundOwnerField = GetPrivateFieldInfo(variableObject, "mBoundOwner"); 246 | var variableBoundOwnerTypeField = GetPrivateFieldInfo(variableObject, "mBoundOwnerType"); 247 | var variableValueField = GetPrivateFieldInfo(variableObject, "mValue"); 248 | 249 | variableBoundMemberNameField.SetValue(variableObject, memberInfo.Name); 250 | variableBoundOwnerField.SetValue(variableObject, owner); 251 | variableBoundOwnerTypeField.SetValue(variableObject, owner.GetType()); 252 | variableValueField.SetValue(variableObject, null); 253 | } 254 | 255 | // ------------------------------------------------------------------------------- 256 | 257 | private static void UnbindVariable(object variableObject) 258 | { 259 | var variableBoundMemberNameField = GetPrivateFieldInfo(variableObject, "mBoundMemberName"); 260 | var variableBoundOwnerField = GetPrivateFieldInfo(variableObject, "mBoundOwner"); 261 | var variableBoundOwnerTypeField = GetPrivateFieldInfo(variableObject, "mBoundOwnerType"); 262 | 263 | variableBoundMemberNameField.SetValue(variableObject, null); 264 | variableBoundOwnerField.SetValue(variableObject, null); 265 | variableBoundOwnerTypeField.SetValue(variableObject, null); 266 | } 267 | 268 | // ------------------------------------------------------------------------------- 269 | } 270 | } 271 | 272 | #endif 273 | -------------------------------------------------------------------------------- /Editor/ActionGraphEditor.cs: -------------------------------------------------------------------------------- 1 | using UnityEngine; 2 | using UnityEngine.SceneManagement; 3 | using UnityEditor; 4 | using UnityEditor.SceneManagement; 5 | using System.Collections.Generic; 6 | 7 | namespace ActionGraph 8 | { 9 | public class ActionGraphEditor : EditorWindow 10 | { 11 | // ------------------------------------------------------------------------------- 12 | 13 | public static Graph CurrentGraph = null; 14 | public static Action CopiedAction = null; 15 | 16 | // ------------------------------------------------------------------------------- 17 | 18 | private Vector2 mPan = Vector2.zero; 19 | private Texture2D mHandleTexture = null; 20 | private Texture2D mArrowTexture = null; 21 | 22 | private Vector2 mHandleRectSize = new Vector2(20, 20); 23 | private Node mNewConnectionStartNode = null; 24 | private Rect mNewConnectionStartRect; 25 | private bool mStartedNewConnectionThisFrame = false; 26 | private bool mInitialised = false; 27 | private Color mDefaultColor = Color.grey; 28 | 29 | private static ActionGraphEditor mInstance = null; 30 | 31 | // ------------------------------------------------------------------------------- 32 | 33 | [MenuItem("Window/ActionGraph Editor")] 34 | public static void ShowEditor() 35 | { 36 | mInstance = EditorWindow.GetWindow(); 37 | mInstance.Init(); 38 | } 39 | 40 | // ------------------------------------------------------------------------------- 41 | 42 | public void Init() 43 | { 44 | mHandleTexture = (Texture2D)AssetDatabase.LoadAssetAtPath("Assets/Source/Textures/EditorCircle.png", typeof(Texture2D)); 45 | mArrowTexture = (Texture2D)AssetDatabase.LoadAssetAtPath("Assets/Source/Textures/EditorArrow.png", typeof(Texture2D)); 46 | 47 | titleContent = new GUIContent("ActionGraph"); 48 | 49 | if (CurrentGraph == null) 50 | { 51 | CurrentGraph = GameObject.FindObjectOfType(); 52 | } 53 | 54 | if (CurrentGraph != null) 55 | { 56 | CurrentGraph.Initialise(); 57 | CurrentGraph.Load(); 58 | mInitialised = true; 59 | mDefaultColor = GUI.backgroundColor; 60 | } 61 | } 62 | 63 | // ------------------------------------------------------------------------------- 64 | 65 | void OnGUI() 66 | { 67 | if (!mInitialised) 68 | { 69 | Init(); 70 | } 71 | 72 | mStartedNewConnectionThisFrame = false; 73 | 74 | if (CurrentGraph == null) 75 | { 76 | EditorGUILayout.LabelField("Please select a Graph from the scene view!"); 77 | return; 78 | } 79 | 80 | if (CurrentGraph.GraphData == null) 81 | { 82 | CurrentGraph.Initialise(); 83 | CurrentGraph.Load(); 84 | } 85 | 86 | DrawMenu(); 87 | 88 | GUI.BeginGroup(new Rect(mPan.x, mPan.y, 100000, 100000)); 89 | 90 | // Draw all the nodes! 91 | BeginWindows(); 92 | for (int i = 0; i < CurrentGraph.GraphData.Nodes.Count; i++) 93 | { 94 | var node = CurrentGraph.GraphData.Nodes[i]; 95 | var windowRect = node.GraphWindowRect; 96 | windowRect.height = 0; // Let the GUILayout.Window function assign the correct height 97 | 98 | if ((CurrentGraph.CurrentNode == CurrentGraph.GraphData.Nodes[i])) 99 | { 100 | GUI.backgroundColor = new Color(0.63f, 0.83f, 0.56f); 101 | } 102 | else if (i == CurrentGraph.GraphData.StartNodeIndex) 103 | { 104 | GUI.backgroundColor = new Color(.6f, .85f, 0.91f); 105 | } 106 | else 107 | { 108 | GUI.backgroundColor = mDefaultColor; 109 | } 110 | 111 | var windowName = (CurrentGraph.GraphData.StartNodeIndex == i) ? "START NODE: " + node.Name : node.Name; 112 | CurrentGraph.GraphData.Nodes[i].GraphWindowRect = GUILayout.Window(i, windowRect, DrawNodeWindow, windowName); 113 | 114 | UpdateNodeResize(node); 115 | DrawHandles(node); 116 | } 117 | EndWindows(); 118 | 119 | // Draw connections between nodes 120 | foreach (var node in CurrentGraph.GraphData.Nodes) 121 | { 122 | foreach (var connection in node.OutgoingConnections) 123 | { 124 | DrawConnection(connection); 125 | } 126 | } 127 | 128 | GUI.EndGroup(); 129 | 130 | if (mNewConnectionStartNode != null && !mStartedNewConnectionThisFrame) 131 | { 132 | // Editor view doesn't update just because the mouse moved so repaint manually in this state 133 | Repaint(); 134 | 135 | var startPos = new Vector2(mNewConnectionStartRect.x + mPan.x, mNewConnectionStartRect.y + mPan.y); 136 | var startRect = new Rect(startPos, mNewConnectionStartRect.size); 137 | var mouseRect = new Rect(Event.current.mousePosition, new Vector2(10, 10)); 138 | DrawBezierCurve(startRect.center, mouseRect.center); 139 | 140 | // Cancel the new connection if the user clicks anywhere on the window background 141 | if (Event.current.type == EventType.MouseDown && (Event.current.button == 0 || Event.current.button == 1)) 142 | { 143 | mNewConnectionStartNode = null; 144 | } 145 | } 146 | else 147 | { 148 | // Context menu for creating new nodes 149 | if (Event.current.type == EventType.MouseDown && Event.current.button == 1) 150 | { 151 | var spawnPosition = Event.current.mousePosition - mPan; 152 | 153 | var menu = new GenericMenu(); 154 | menu.AddItem(new GUIContent("Standard Node"), false, () => { CreateStandardNode(spawnPosition); }); 155 | menu.AddItem(new GUIContent("Transition Node"), false, () => { CreateTransitionNode(spawnPosition); }); 156 | menu.ShowAsContext(); 157 | } 158 | 159 | // Grab and pan all the visual elements of the graph 160 | if (Event.current.button == 0 ) 161 | { 162 | if (Event.current.type == EventType.MouseDrag) 163 | { 164 | mPan.x += Event.current.delta.x; 165 | mPan.y += Event.current.delta.y; 166 | Repaint(); 167 | } 168 | else if (Event.current.type == EventType.MouseUp) 169 | { 170 | Selection.SetActiveObjectWithContext(CurrentGraph.gameObject, null); 171 | } 172 | } 173 | } 174 | } 175 | 176 | // ------------------------------------------------------------------------------- 177 | 178 | void DrawNodeWindow(int id) 179 | { 180 | var node = CurrentGraph.GraphData.Nodes[id]; 181 | 182 | // Is the user trying to create a new connection, possibly with this node? 183 | if (mNewConnectionStartNode != null && mNewConnectionStartNode != node) 184 | { 185 | if (Event.current.type == EventType.MouseDown && Event.current.button == 0) 186 | { 187 | // Assuming we're not already connected to the given node. 188 | if (mNewConnectionStartNode.GetOutgoingConnectionToNode(node) == null) 189 | { 190 | // Create a new conneciton between the two nodes! 191 | var newConnection = new Connection { StartNode = mNewConnectionStartNode, EndNode = node }; 192 | newConnection.StartNode.OutgoingConnections.Add(newConnection); 193 | newConnection.EndNode.IncomingConnections.Add(newConnection); 194 | mNewConnectionStartNode = null; 195 | ShowConnectionInspector(newConnection); 196 | } 197 | } 198 | } 199 | else 200 | { 201 | // Has this node been clicked on? Save change in position 202 | Event currentEvent = Event.current; 203 | if (currentEvent.type == EventType.MouseDown && currentEvent.button == 0) 204 | { 205 | SaveGraph(); 206 | } 207 | 208 | // Context menu for modifying existing node 209 | if (currentEvent.type == EventType.MouseDown && currentEvent.button == 1) 210 | { 211 | var menu = new GenericMenu(); 212 | menu.AddItem(new GUIContent("Delete"), false, () => { DeleteNode(id); }); 213 | menu.AddItem(new GUIContent("Make Start Node"), false, () => { SetStartNode(id); }); 214 | menu.ShowAsContext(); 215 | } 216 | } 217 | 218 | // TODO: This is not very extensible! OnGUI logic for Nodes lives in extension methods in the 219 | // editor project, but calling directly on the base node reference in our list will always 220 | // call the default implementation.. haven't find a nice fix for this yet! 221 | var transitionNode = (node as TransitionNode); 222 | if (transitionNode != null) 223 | { 224 | transitionNode.OnGUI(); 225 | } 226 | else 227 | { 228 | node.OnGUI(); 229 | } 230 | 231 | GUI.DragWindow(); 232 | } 233 | 234 | // ------------------------------------------------------------------------------- 235 | 236 | void DrawConnection(Connection connection) 237 | { 238 | Node startnode = connection.StartNode; 239 | Node endNode = connection.EndNode; 240 | 241 | Vector2 startPos = Vector2.zero; 242 | Vector2 endPos = Vector2.zero; 243 | float minSqrDistance = float.MaxValue; 244 | 245 | // Find the shortest path between the two nodes 246 | foreach (var startNodeHandle in startnode.ConnectionHandles) 247 | { 248 | foreach (var endNodeHandle in endNode.ConnectionHandles) 249 | { 250 | var sqrDistance = Vector2.SqrMagnitude(startNodeHandle.Position - endNodeHandle.Position); 251 | if (sqrDistance < minSqrDistance) 252 | { 253 | minSqrDistance = sqrDistance; 254 | startPos = startNodeHandle.DisplayRect.center; 255 | endPos = endNodeHandle.DisplayRect.center; 256 | } 257 | } 258 | } 259 | 260 | DrawBezierCurve(startPos, endPos); 261 | 262 | var curveMidPoint = startPos + ((endPos - startPos) * 0.5f); 263 | var curveMidPointRect = new Rect(curveMidPoint, new Vector2(32, 32)); 264 | 265 | // Draw connection icon used to display connection in the editor 266 | GUI.DrawTexture(curveMidPointRect, mHandleTexture); 267 | EditorGUIUtility.AddCursorRect(curveMidPointRect, MouseCursor.Text); 268 | 269 | if (Event.current.button == 0 && Event.current.type == EventType.MouseDown && 270 | curveMidPointRect.Contains(Event.current.mousePosition)) 271 | { 272 | ShowConnectionInspector(connection); 273 | } 274 | 275 | // Draw directional arrow 276 | { 277 | Matrix4x4 matrixBackup = GUI.matrix; 278 | float angle = Mathf.Atan2(endPos.y - startPos.y, endPos.x - startPos.x) * 180 / Mathf.PI; 279 | GUIUtility.RotateAroundPivot(angle, curveMidPoint); 280 | GUI.DrawTexture(curveMidPointRect, mArrowTexture); 281 | GUI.matrix = matrixBackup; 282 | } 283 | } 284 | 285 | // ------------------------------------------------------------------------------- 286 | 287 | void DrawBezierCurve(Vector2 startPos, Vector2 endPos) 288 | { 289 | Vector2 startToEnd = (endPos - startPos); 290 | float directionFactor = Mathf.Clamp(startToEnd.magnitude, 20f, 80f); 291 | Vector2 projection = Vector3.Project(startToEnd.normalized, Vector3.right); 292 | 293 | Vector2 startTan = startPos + projection * directionFactor; 294 | Vector2 endTan = endPos - projection * directionFactor; 295 | 296 | // Draw a shadow 297 | Color shadowCol = new Color(0, 0, 0, 0.06f); 298 | for (int i = 0; i < 3; i++) 299 | { 300 | Handles.DrawBezier(startPos, endPos, startTan, endTan, shadowCol, null, (i + 1) * 5); 301 | } 302 | 303 | Handles.DrawBezier(startPos, endPos, startTan, endTan, Color.black, null, 1); 304 | } 305 | 306 | // ------------------------------------------------------------------------------- 307 | 308 | void DrawHandles(Node node) 309 | { 310 | var windowRect = node.GraphWindowRect; 311 | var handleHalfSize = mHandleRectSize * 0.5f; 312 | var leftAndRightHandleYPos = (windowRect.y + windowRect.height * 0.5f) - handleHalfSize.y; 313 | var topAndBottomHandleXPos = (windowRect.x + windowRect.width * 0.5f) - handleHalfSize.x; 314 | 315 | // Initialise this node's list of connection handles if we haven't already done so 316 | if (node.ConnectionHandles == null || node.ConnectionHandles.Count != 4) 317 | { 318 | node.ConnectionHandles = new List{new Node.ConnectionHandle(), 319 | new Node.ConnectionHandle(), new Node.ConnectionHandle(), new Node.ConnectionHandle() }; 320 | } 321 | 322 | // Calculate positions for all connection handles 323 | node.ConnectionHandles[0].Position = (new Vector2(windowRect.x - handleHalfSize.x, leftAndRightHandleYPos)); // Left 324 | node.ConnectionHandles[1].Position = (new Vector2(windowRect.x + windowRect.width - handleHalfSize.x, leftAndRightHandleYPos)); // Right 325 | node.ConnectionHandles[2].Position = (new Vector2(topAndBottomHandleXPos, windowRect.y - handleHalfSize.y)); // Top 326 | node.ConnectionHandles[3].Position = (new Vector2(topAndBottomHandleXPos, windowRect.y + windowRect.height - handleHalfSize.y)); // Bottom 327 | 328 | // Create an interactive rect area and texture for each handle 329 | for (int i = 0; i < 4; i++) 330 | { 331 | var handleRect = new Rect(node.ConnectionHandles[i].Position, mHandleRectSize); 332 | node.ConnectionHandles[i].DisplayRect = handleRect; 333 | GUI.DrawTexture(handleRect, mHandleTexture); 334 | EditorGUIUtility.AddCursorRect(handleRect, MouseCursor.ArrowPlus); 335 | } 336 | 337 | // Check for a user clicking on a handle 338 | if (Event.current.button == 0 && Event.current.type == EventType.MouseDown) 339 | { 340 | foreach (var connectionHandle in node.ConnectionHandles) 341 | { 342 | if (connectionHandle.DisplayRect.Contains(Event.current.mousePosition)) 343 | { 344 | mNewConnectionStartNode = node; 345 | mNewConnectionStartRect = connectionHandle.DisplayRect; 346 | mStartedNewConnectionThisFrame = true; 347 | break; 348 | } 349 | } 350 | } 351 | } 352 | 353 | // ------------------------------------------------------------------------------- 354 | 355 | void DrawMenu() 356 | { 357 | GUILayout.BeginHorizontal(EditorStyles.toolbar); 358 | 359 | if (GUILayout.Button("Save", EditorStyles.toolbarButton)) 360 | { 361 | SaveGraph(); 362 | } 363 | GUILayout.FlexibleSpace(); 364 | 365 | if (GUILayout.Button("Settings", EditorStyles.toolbarDropDown)) 366 | { 367 | GenericMenu settingsMenu = new GenericMenu(); 368 | settingsMenu.AddItem(new GUIContent("Load"), false, LoadGraph); 369 | settingsMenu.DropDown(new Rect(Screen.width - 200 - 40, 0, 0, 16)); 370 | } 371 | 372 | GUILayout.EndHorizontal(); 373 | } 374 | 375 | // ------------------------------------------------------------------------------- 376 | 377 | void UpdateNodeResize(Node node) 378 | { 379 | Rect resizeAreaRect = node.GraphWindowRect; 380 | resizeAreaRect.x += resizeAreaRect.width * 0.9f; 381 | resizeAreaRect.y += resizeAreaRect.height * 0.9f; 382 | resizeAreaRect.width *= 0.1f; 383 | resizeAreaRect.height *= 0.1f; 384 | 385 | EditorGUIUtility.AddCursorRect(resizeAreaRect, MouseCursor.ResizeUpLeft); 386 | 387 | // KB TODO: RESIZE ON DRAG 388 | if (Event.current.type == EventType.MouseDrag && Event.current.button == 0) 389 | { 390 | //MyGraph.GraphData.Nodes[i].GraphWindowRect.width += 0.1f; 391 | } 392 | } 393 | 394 | // ------------------------------------------------------------------------------- 395 | 396 | private void CreateStandardNode(Vector2 spawnPosition) 397 | { 398 | var newStandardNode = new Node(); 399 | newStandardNode.GraphWindowRect.position = spawnPosition; 400 | CurrentGraph.GraphData.Nodes.Add(newStandardNode); 401 | MarkAsDirty(); 402 | } 403 | 404 | // ------------------------------------------------------------------------------- 405 | 406 | private void CreateTransitionNode(Vector2 spawnPosition) 407 | { 408 | var newTransitionNode = new TransitionNode(); 409 | newTransitionNode.GraphWindowRect.position = spawnPosition; 410 | CurrentGraph.GraphData.Nodes.Add(newTransitionNode); 411 | MarkAsDirty(); 412 | } 413 | 414 | // ------------------------------------------------------------------------------- 415 | 416 | private void DeleteNode(int id) 417 | { 418 | ActionGraphInspector.Clear(); 419 | CurrentGraph.GraphData.Nodes[id].OnDelete(); 420 | CurrentGraph.GraphData.Nodes.RemoveAt(id); 421 | MarkAsDirty(); 422 | 423 | if (CurrentGraph.GraphData.StartNodeIndex == id) 424 | { 425 | Debug.Log("Just deleted graph's start node, reverting to default start node (id 0)"); 426 | SetStartNode(0); 427 | } 428 | } 429 | 430 | // ------------------------------------------------------------------------------- 431 | 432 | private void SetStartNode(int id) 433 | { 434 | CurrentGraph.GraphData.StartNodeIndex = id; 435 | } 436 | 437 | // ------------------------------------------------------------------------------- 438 | 439 | private void SaveGraph() 440 | { 441 | if (!Application.isPlaying) 442 | { 443 | CurrentGraph.Initialise(); 444 | CurrentGraph.Save(); 445 | MarkAsDirty(); 446 | } 447 | } 448 | 449 | // ------------------------------------------------------------------------------- 450 | 451 | private void LoadGraph() 452 | { 453 | if (!Application.isPlaying && CurrentGraph != null) 454 | { 455 | CurrentGraph.Load(); 456 | } 457 | } 458 | 459 | // ------------------------------------------------------------------------------- 460 | 461 | public static void MarkAsDirty(bool repaint = false) 462 | { 463 | if (!Application.isPlaying && CurrentGraph != null) 464 | { 465 | EditorUtility.SetDirty(CurrentGraph); 466 | EditorSceneManager.MarkSceneDirty(SceneManager.GetActiveScene()); 467 | 468 | if (repaint && mInstance != null) 469 | { 470 | mInstance.Repaint(); 471 | } 472 | } 473 | } 474 | 475 | // ------------------------------------------------------------------------------- 476 | 477 | private void ShowConnectionInspector(Connection connection) 478 | { 479 | ActionGraphInspector.CurrentGraph = ActionGraphEditor.CurrentGraph; 480 | ActionGraphInspector.SetCurrentConnection(connection); 481 | ActionGraphInspector.ShowEditor(); 482 | } 483 | 484 | // ------------------------------------------------------------------------------- 485 | } 486 | } 487 | --------------------------------------------------------------------------------