Browse Source

Merge pull request #530 from snozbot/refactor-properties

Refactor properties to use [SerializeField] protected and unified comment style.
master
Chris Gregan 9 years ago committed by GitHub
parent
commit
f8d4aed278
  1. 22
      Assets/Fungus/Animation/Scripts/Commands/PlayAnimState.cs
  2. 16
      Assets/Fungus/Animation/Scripts/Commands/ResetAnimTrigger.cs
  3. 18
      Assets/Fungus/Animation/Scripts/Commands/SetAnimBool.cs
  4. 18
      Assets/Fungus/Animation/Scripts/Commands/SetAnimFloat.cs
  5. 18
      Assets/Fungus/Animation/Scripts/Commands/SetAnimInteger.cs
  6. 16
      Assets/Fungus/Animation/Scripts/Commands/SetAnimTrigger.cs
  7. 18
      Assets/Fungus/Audio/Editor/ControlAudioEditor.cs
  8. 31
      Assets/Fungus/Audio/Scripts/Commands/ControlAudio.cs
  9. 19
      Assets/Fungus/Audio/Scripts/Commands/PlayMusic.cs
  10. 17
      Assets/Fungus/Audio/Scripts/Commands/PlaySound.cs
  11. 52
      Assets/Fungus/Audio/Scripts/Commands/PlayUsfxrSound.cs
  12. 17
      Assets/Fungus/Audio/Scripts/Commands/SetAudioPitch.cs
  13. 17
      Assets/Fungus/Audio/Scripts/Commands/SetAudioVolume.cs
  14. 11
      Assets/Fungus/Audio/Scripts/Commands/StopMusic.cs
  15. 76
      Assets/Fungus/Audio/Scripts/MusicController.cs
  16. 9
      Assets/Fungus/Camera/Editor/CameraMenuItems.cs
  17. 24
      Assets/Fungus/Camera/Editor/ViewEditor.cs
  18. 158
      Assets/Fungus/Camera/Scripts/CameraController.cs
  19. 35
      Assets/Fungus/Camera/Scripts/Commands/FadeScreen.cs
  20. 37
      Assets/Fungus/Camera/Scripts/Commands/FadeToView.cs
  21. 14
      Assets/Fungus/Camera/Scripts/Commands/Fullscreen.cs
  22. 29
      Assets/Fungus/Camera/Scripts/Commands/MoveToView.cs
  23. 19
      Assets/Fungus/Camera/Scripts/Commands/ShakeCamera.cs
  24. 22
      Assets/Fungus/Camera/Scripts/Commands/StartSwipe.cs
  25. 12
      Assets/Fungus/Camera/Scripts/Commands/StopSwipe.cs
  26. 45
      Assets/Fungus/Camera/Scripts/View.cs
  27. 22
      Assets/Fungus/Flowchart/Editor/AssetModProcessor.cs
  28. 151
      Assets/Fungus/Flowchart/Editor/BlockEditor.cs
  29. 39
      Assets/Fungus/Flowchart/Editor/BlockInspector.cs
  30. 9
      Assets/Fungus/Flowchart/Editor/CallEditor.cs
  31. 30
      Assets/Fungus/Flowchart/Editor/CommandEditor.cs
  32. 58
      Assets/Fungus/Flowchart/Editor/CommandListAdaptor.cs
  33. 18
      Assets/Fungus/Flowchart/Editor/CustomGUI.cs
  34. 9
      Assets/Fungus/Flowchart/Editor/EditorExtensions.cs
  35. 8
      Assets/Fungus/Flowchart/Editor/EditorZoomArea.cs
  36. 17
      Assets/Fungus/Flowchart/Editor/EventHandlerEditor.cs
  37. 6
      Assets/Fungus/Flowchart/Editor/Extensions/SerializedPropertyExtensions.cs
  38. 49
      Assets/Fungus/Flowchart/Editor/FlowchartEditor.cs
  39. 16
      Assets/Fungus/Flowchart/Editor/FlowchartMenuItems.cs
  40. 220
      Assets/Fungus/Flowchart/Editor/FlowchartWindow.cs
  41. 8
      Assets/Fungus/Flowchart/Editor/FungusEditorResources.cs
  42. 20
      Assets/Fungus/Flowchart/Editor/GLDraw.cs
  43. 10
      Assets/Fungus/Flowchart/Editor/IfEditor.cs
  44. 9
      Assets/Fungus/Flowchart/Editor/InvokeEventEditor.cs
  45. 45
      Assets/Fungus/Flowchart/Editor/InvokeMethodEditor.cs
  46. 17
      Assets/Fungus/Flowchart/Editor/LabelEditor.cs
  47. 10
      Assets/Fungus/Flowchart/Editor/SetVariableEditor.cs
  48. 16
      Assets/Fungus/Flowchart/Editor/VariableEditor.cs
  49. 24
      Assets/Fungus/Flowchart/Editor/VariableListAdaptor.cs
  50. 157
      Assets/Fungus/Flowchart/Scripts/Block.cs
  51. 221
      Assets/Fungus/Flowchart/Scripts/Command.cs
  52. 20
      Assets/Fungus/Flowchart/Scripts/CommandCopyBuffer.cs
  53. 31
      Assets/Fungus/Flowchart/Scripts/Commands/Break.cs
  54. 30
      Assets/Fungus/Flowchart/Scripts/Commands/Call.cs
  55. 22
      Assets/Fungus/Flowchart/Scripts/Commands/CallMethod.cs
  56. 16
      Assets/Fungus/Flowchart/Scripts/Commands/Comment.cs
  57. 11
      Assets/Fungus/Flowchart/Scripts/Commands/Condition.cs
  58. 15
      Assets/Fungus/Flowchart/Scripts/Commands/DebugLog.cs
  59. 16
      Assets/Fungus/Flowchart/Scripts/Commands/DeleteSaveKey.cs
  60. 14
      Assets/Fungus/Flowchart/Scripts/Commands/Destroy.cs
  61. 24
      Assets/Fungus/Flowchart/Scripts/Commands/Else.cs
  62. 27
      Assets/Fungus/Flowchart/Scripts/Commands/ElseIf.cs
  63. 22
      Assets/Fungus/Flowchart/Scripts/Commands/End.cs
  64. 39
      Assets/Fungus/Flowchart/Scripts/Commands/If.cs
  65. 46
      Assets/Fungus/Flowchart/Scripts/Commands/InvokeEvent.cs
  66. 90
      Assets/Fungus/Flowchart/Scripts/Commands/InvokeMethod.cs
  67. 20
      Assets/Fungus/Flowchart/Scripts/Commands/Jump.cs
  68. 16
      Assets/Fungus/Flowchart/Scripts/Commands/Label.cs
  69. 31
      Assets/Fungus/Flowchart/Scripts/Commands/LoadScene.cs
  70. 26
      Assets/Fungus/Flowchart/Scripts/Commands/LoadVariable.cs
  71. 14
      Assets/Fungus/Flowchart/Scripts/Commands/OpenURL.cs
  72. 12
      Assets/Fungus/Flowchart/Scripts/Commands/Quit.cs
  73. 21
      Assets/Fungus/Flowchart/Scripts/Commands/RandomFloat.cs
  74. 21
      Assets/Fungus/Flowchart/Scripts/Commands/RandomInteger.cs
  75. 20
      Assets/Fungus/Flowchart/Scripts/Commands/ReadTextFile.cs
  76. 16
      Assets/Fungus/Flowchart/Scripts/Commands/Reset.cs
  77. 28
      Assets/Fungus/Flowchart/Scripts/Commands/SaveVariable.cs
  78. 15
      Assets/Fungus/Flowchart/Scripts/Commands/SendMessage.cs
  79. 16
      Assets/Fungus/Flowchart/Scripts/Commands/SetActive.cs
  80. 20
      Assets/Fungus/Flowchart/Scripts/Commands/SetSaveProfile.cs
  81. 52
      Assets/Fungus/Flowchart/Scripts/Commands/SetVariable.cs
  82. 22
      Assets/Fungus/Flowchart/Scripts/Commands/SpawnObject.cs
  83. 12
      Assets/Fungus/Flowchart/Scripts/Commands/Stop.cs
  84. 16
      Assets/Fungus/Flowchart/Scripts/Commands/StopBlock.cs
  85. 15
      Assets/Fungus/Flowchart/Scripts/Commands/StopFlowchart.cs
  86. 14
      Assets/Fungus/Flowchart/Scripts/Commands/Wait.cs
  87. 25
      Assets/Fungus/Flowchart/Scripts/Commands/While.cs
  88. 53
      Assets/Fungus/Flowchart/Scripts/EventHandler.cs
  89. 12
      Assets/Fungus/Flowchart/Scripts/EventHandlers/FlowchartEnabled.cs
  90. 12
      Assets/Fungus/Flowchart/Scripts/EventHandlers/GameStarted.cs
  91. 14
      Assets/Fungus/Flowchart/Scripts/EventHandlers/KeyPressed.cs
  92. 13
      Assets/Fungus/Flowchart/Scripts/EventHandlers/MessageReceived.cs
  93. 565
      Assets/Fungus/Flowchart/Scripts/Flowchart.cs
  94. 18
      Assets/Fungus/Flowchart/Scripts/FungusState.cs
  95. 15
      Assets/Fungus/Flowchart/Scripts/Node.cs
  96. 29
      Assets/Fungus/Flowchart/Scripts/SceneLoader.cs
  97. 15
      Assets/Fungus/Flowchart/Scripts/StringFormatter.cs
  98. 38
      Assets/Fungus/Flowchart/Scripts/Variable.cs
  99. 20
      Assets/Fungus/Flowchart/Scripts/VariableTypes/AnimatorVariable.cs
  100. 20
      Assets/Fungus/Flowchart/Scripts/VariableTypes/AudioSourceVariable.cs
  101. Some files were not shown because too many files have changed in this diff Show More

22
Assets/Fungus/Animation/Scripts/Commands/PlayAnimState.cs

@ -1,14 +1,13 @@
/** // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
using UnityEngine; using UnityEngine;
using System;
using System.Collections;
namespace Fungus namespace Fungus
{ {
/// <summary>
/// Plays a state of an animator according to the state name.
/// </summary>
[CommandInfo("Animation", [CommandInfo("Animation",
"Play Anim State", "Play Anim State",
"Plays a state of an animator according to the state name")] "Plays a state of an animator according to the state name")]
@ -16,16 +15,16 @@ namespace Fungus
public class PlayAnimState : Command public class PlayAnimState : Command
{ {
[Tooltip("Reference to an Animator component in a game object")] [Tooltip("Reference to an Animator component in a game object")]
public AnimatorData animator = new AnimatorData(); [SerializeField] protected AnimatorData animator = new AnimatorData();
[Tooltip("Name of the state you want to play")] [Tooltip("Name of the state you want to play")]
public StringData stateName = new StringData(); [SerializeField] protected StringData stateName = new StringData();
[Tooltip("Layer to play animation on")] [Tooltip("Layer to play animation on")]
public IntegerData layer = new IntegerData(-1); [SerializeField] protected IntegerData layer = new IntegerData(-1);
[Tooltip("Start time of animation")] [Tooltip("Start time of animation")]
public FloatData time = new FloatData(0f); [SerializeField] protected FloatData time = new FloatData(0f);
public override void OnEnter() public override void OnEnter()
{ {
@ -51,7 +50,6 @@ namespace Fungus
{ {
return new Color32(170, 204, 169, 255); return new Color32(170, 204, 169, 255);
} }
} }
} }

16
Assets/Fungus/Animation/Scripts/Commands/ResetAnimTrigger.cs

@ -1,15 +1,14 @@
/** // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
using UnityEngine; using UnityEngine;
using UnityEngine.Serialization; using UnityEngine.Serialization;
using System;
using System.Collections;
namespace Fungus namespace Fungus
{ {
/// <summary>
/// Resets a trigger parameter on an Animator component.
/// </summary>
[CommandInfo("Animation", [CommandInfo("Animation",
"Reset Anim Trigger", "Reset Anim Trigger",
"Resets a trigger parameter on an Animator component.")] "Resets a trigger parameter on an Animator component.")]
@ -18,10 +17,10 @@ namespace Fungus
public class ResetAnimTrigger : Command public class ResetAnimTrigger : Command
{ {
[Tooltip("Reference to an Animator component in a game object")] [Tooltip("Reference to an Animator component in a game object")]
public AnimatorData _animator; [SerializeField] protected AnimatorData _animator;
[Tooltip("Name of the trigger Animator parameter that will be reset")] [Tooltip("Name of the trigger Animator parameter that will be reset")]
public StringData _parameterName; [SerializeField] protected StringData _parameterName;
public override void OnEnter() public override void OnEnter()
{ {
@ -70,5 +69,4 @@ namespace Fungus
#endregion #endregion
} }
} }

18
Assets/Fungus/Animation/Scripts/Commands/SetAnimBool.cs

@ -1,15 +1,14 @@
/** // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
using UnityEngine; using UnityEngine;
using UnityEngine.Serialization; using UnityEngine.Serialization;
using System;
using System.Collections;
namespace Fungus namespace Fungus
{ {
/// <summary>
/// Sets a boolean parameter on an Animator component to control a Unity animation"
/// </summary>
[CommandInfo("Animation", [CommandInfo("Animation",
"Set Anim Bool", "Set Anim Bool",
"Sets a boolean parameter on an Animator component to control a Unity animation")] "Sets a boolean parameter on an Animator component to control a Unity animation")]
@ -18,13 +17,13 @@ namespace Fungus
public class SetAnimBool : Command public class SetAnimBool : Command
{ {
[Tooltip("Reference to an Animator component in a game object")] [Tooltip("Reference to an Animator component in a game object")]
public AnimatorData _animator; [SerializeField] protected AnimatorData _animator;
[Tooltip("Name of the boolean Animator parameter that will have its value changed")] [Tooltip("Name of the boolean Animator parameter that will have its value changed")]
public StringData _parameterName; [SerializeField] protected StringData _parameterName;
[Tooltip("The boolean value to set the parameter to")] [Tooltip("The boolean value to set the parameter to")]
public BooleanData value; [SerializeField] protected BooleanData value;
public override void OnEnter() public override void OnEnter()
{ {
@ -73,5 +72,4 @@ namespace Fungus
#endregion #endregion
} }
} }

18
Assets/Fungus/Animation/Scripts/Commands/SetAnimFloat.cs

@ -1,15 +1,14 @@
/** // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
using UnityEngine; using UnityEngine;
using UnityEngine.Serialization; using UnityEngine.Serialization;
using System;
using System.Collections;
namespace Fungus namespace Fungus
{ {
/// <summary>
/// Sets a float parameter on an Animator component to control a Unity animation.
/// </summary>
[CommandInfo("Animation", [CommandInfo("Animation",
"Set Anim Float", "Set Anim Float",
"Sets a float parameter on an Animator component to control a Unity animation")] "Sets a float parameter on an Animator component to control a Unity animation")]
@ -18,13 +17,13 @@ namespace Fungus
public class SetAnimFloat : Command public class SetAnimFloat : Command
{ {
[Tooltip("Reference to an Animator component in a game object")] [Tooltip("Reference to an Animator component in a game object")]
public AnimatorData _animator; [SerializeField] protected AnimatorData _animator;
[Tooltip("Name of the float Animator parameter that will have its value changed")] [Tooltip("Name of the float Animator parameter that will have its value changed")]
public StringData _parameterName; [SerializeField] protected StringData _parameterName;
[Tooltip("The float value to set the parameter to")] [Tooltip("The float value to set the parameter to")]
public FloatData value; [SerializeField] protected FloatData value;
public override void OnEnter() public override void OnEnter()
{ {
@ -73,5 +72,4 @@ namespace Fungus
#endregion #endregion
} }
} }

18
Assets/Fungus/Animation/Scripts/Commands/SetAnimInteger.cs

@ -1,15 +1,14 @@
/** // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
using UnityEngine; using UnityEngine;
using UnityEngine.Serialization; using UnityEngine.Serialization;
using System;
using System.Collections;
namespace Fungus namespace Fungus
{ {
/// <summary>
/// Sets an integer parameter on an Animator component to control a Unity animation.
/// </summary>
[CommandInfo("Animation", [CommandInfo("Animation",
"Set Anim Integer", "Set Anim Integer",
"Sets an integer parameter on an Animator component to control a Unity animation")] "Sets an integer parameter on an Animator component to control a Unity animation")]
@ -18,13 +17,13 @@ namespace Fungus
public class SetAnimInteger : Command public class SetAnimInteger : Command
{ {
[Tooltip("Reference to an Animator component in a game object")] [Tooltip("Reference to an Animator component in a game object")]
public AnimatorData _animator; [SerializeField] protected AnimatorData _animator;
[Tooltip("Name of the integer Animator parameter that will have its value changed")] [Tooltip("Name of the integer Animator parameter that will have its value changed")]
public StringData _parameterName; [SerializeField] protected StringData _parameterName;
[Tooltip("The integer value to set the parameter to")] [Tooltip("The integer value to set the parameter to")]
public IntegerData value; [SerializeField] protected IntegerData value;
public override void OnEnter() public override void OnEnter()
{ {
@ -73,5 +72,4 @@ namespace Fungus
#endregion #endregion
} }
} }

16
Assets/Fungus/Animation/Scripts/Commands/SetAnimTrigger.cs

@ -1,15 +1,14 @@
/** // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
using UnityEngine; using UnityEngine;
using UnityEngine.Serialization; using UnityEngine.Serialization;
using System;
using System.Collections;
namespace Fungus namespace Fungus
{ {
/// <summary>
/// Sets a trigger parameter on an Animator component to control a Unity animation.
/// </summary>
[CommandInfo("Animation", [CommandInfo("Animation",
"Set Anim Trigger", "Set Anim Trigger",
"Sets a trigger parameter on an Animator component to control a Unity animation")] "Sets a trigger parameter on an Animator component to control a Unity animation")]
@ -18,10 +17,10 @@ namespace Fungus
public class SetAnimTrigger : Command public class SetAnimTrigger : Command
{ {
[Tooltip("Reference to an Animator component in a game object")] [Tooltip("Reference to an Animator component in a game object")]
public AnimatorData _animator; [SerializeField] protected AnimatorData _animator;
[Tooltip("Name of the trigger Animator parameter that will have its value changed")] [Tooltip("Name of the trigger Animator parameter that will have its value changed")]
public StringData _parameterName; [SerializeField] protected StringData _parameterName;
public override void OnEnter() public override void OnEnter()
{ {
@ -70,5 +69,4 @@ namespace Fungus
#endregion #endregion
} }
} }

18
Assets/Fungus/Audio/Editor/ControlAudioEditor.cs

@ -1,18 +1,8 @@
/** // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
using UnityEditor; using UnityEditor;
using UnityEditorInternal;
using UnityEngine; using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Events;
using System;
using System.Collections;
using System.Collections.Generic;
using Rotorz.ReorderableList;
namespace Fungus namespace Fungus
{ {
@ -49,11 +39,11 @@ namespace Fungus
EditorGUILayout.PropertyField(controlProp); EditorGUILayout.PropertyField(controlProp);
EditorGUILayout.PropertyField(audioSourceProp); EditorGUILayout.PropertyField(audioSourceProp);
string fadeLabel = "Fade Out Duration"; string fadeLabel = "Fade Out Duration";
if (t.control != ControlAudio.controlType.StopLoop && t.control != ControlAudio.controlType.PauseLoop) if (t.Control != ControlAudio.controlType.StopLoop && t.Control != ControlAudio.controlType.PauseLoop)
{ {
fadeLabel = "Fade In Duration"; fadeLabel = "Fade In Duration";
string volumeLabel = "End Volume"; string volumeLabel = "End Volume";
if (t.control == ControlAudio.controlType.ChangeVolume) if (t.Control == ControlAudio.controlType.ChangeVolume)
{ {
fadeLabel = "Fade Duration"; fadeLabel = "Fade Duration";
volumeLabel = "New Volume"; volumeLabel = "New Volume";

31
Assets/Fungus/Audio/Scripts/Commands/ControlAudio.cs

@ -1,7 +1,5 @@
/** // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
using UnityEngine; using UnityEngine;
using UnityEngine.Serialization; using UnityEngine.Serialization;
@ -9,6 +7,9 @@ using System.Collections;
namespace Fungus namespace Fungus
{ {
/// <summary>
/// Plays, loops, or stops an audiosource. Any AudioSources with the same tag as the target Audio Source will automatically be stoped.
/// </summary>
[CommandInfo("Audio", [CommandInfo("Audio",
"Control Audio", "Control Audio",
"Plays, loops, or stops an audiosource. Any AudioSources with the same tag as the target Audio Source will automatically be stoped.")] "Plays, loops, or stops an audiosource. Any AudioSources with the same tag as the target Audio Source will automatically be stoped.")]
@ -25,24 +26,25 @@ namespace Fungus
} }
[Tooltip("What to do to audio")] [Tooltip("What to do to audio")]
public controlType control; [SerializeField] protected controlType control;
public controlType Control { get { return control; } }
[Tooltip("Audio clip to play")] [Tooltip("Audio clip to play")]
public AudioSourceData _audioSource; [SerializeField] protected AudioSourceData _audioSource;
[Range(0,1)] [Range(0,1)]
[Tooltip("Start audio at this volume")] [Tooltip("Start audio at this volume")]
public float startVolume = 1; [SerializeField] protected float startVolume = 1;
[Range(0,1)] [Range(0,1)]
[Tooltip("End audio at this volume")] [Tooltip("End audio at this volume")]
public float endVolume = 1; [SerializeField] protected float endVolume = 1;
[Tooltip("Time to fade between current volume level and target volume level.")] [Tooltip("Time to fade between current volume level and target volume level.")]
public float fadeDuration; [SerializeField] protected float fadeDuration;
[Tooltip("Wait until this command has finished before executing the next command.")] [Tooltip("Wait until this command has finished before executing the next command.")]
public bool waitUntilFinished = false; [SerializeField] protected bool waitUntilFinished = false;
public override void OnEnter() public override void OnEnter()
{ {
@ -83,10 +85,8 @@ namespace Fungus
} }
} }
/** // If there's other music playing in the scene, assign it the same tag as the new music you want to play and
* If there's other music playing in the scene, assign it the same tag as the new music you want to play and // the old music will be automatically stopped.
* the old music will be automatically stopped.
*/
protected void StopAudioWithSameTag() protected void StopAudioWithSameTag()
{ {
// Don't stop audio if there's no tag assigned // Don't stop audio if there's no tag assigned
@ -287,6 +287,5 @@ namespace Fungus
} }
#endregion #endregion
} }
} }

19
Assets/Fungus/Audio/Scripts/Commands/PlayMusic.cs

@ -1,13 +1,13 @@
/** // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
using UnityEngine; using UnityEngine;
using System.Collections;
namespace Fungus namespace Fungus
{ {
/// <summary>
/// Plays looping game music. If any game music is already playing, it is stopped. Game music will continue playing across scene loads.
/// </summary>
[CommandInfo("Audio", [CommandInfo("Audio",
"Play Music", "Play Music",
"Plays looping game music. If any game music is already playing, it is stopped. Game music will continue playing across scene loads.")] "Plays looping game music. If any game music is already playing, it is stopped. Game music will continue playing across scene loads.")]
@ -15,16 +15,16 @@ namespace Fungus
public class PlayMusic : Command public class PlayMusic : Command
{ {
[Tooltip("Music sound clip to play")] [Tooltip("Music sound clip to play")]
public AudioClip musicClip; [SerializeField] protected AudioClip musicClip;
[Tooltip("Time to begin playing in seconds. If the audio file is compressed, the time index may be inaccurate.")] [Tooltip("Time to begin playing in seconds. If the audio file is compressed, the time index may be inaccurate.")]
public float atTime; [SerializeField] protected float atTime;
[Tooltip("The music will start playing again at end.")] [Tooltip("The music will start playing again at end.")]
public bool loop = true; [SerializeField] protected bool loop = true;
[Tooltip("Length of time to fade out previous playing music.")] [Tooltip("Length of time to fade out previous playing music.")]
public float fadeDuration = 1f; [SerializeField] protected float fadeDuration = 1f;
public override void OnEnter() public override void OnEnter()
{ {
@ -53,5 +53,4 @@ namespace Fungus
return new Color32(242, 209, 176, 255); return new Color32(242, 209, 176, 255);
} }
} }
} }

17
Assets/Fungus/Audio/Scripts/Commands/PlaySound.cs

@ -1,13 +1,13 @@
/** // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
using UnityEngine; using UnityEngine;
using System.Collections;
namespace Fungus namespace Fungus
{ {
/// <summary>
/// Plays a once-off sound effect. Multiple sound effects can be played at the same time.
/// </summary>
[CommandInfo("Audio", [CommandInfo("Audio",
"Play Sound", "Play Sound",
"Plays a once-off sound effect. Multiple sound effects can be played at the same time.")] "Plays a once-off sound effect. Multiple sound effects can be played at the same time.")]
@ -15,14 +15,14 @@ namespace Fungus
public class PlaySound : Command public class PlaySound : Command
{ {
[Tooltip("Sound effect clip to play")] [Tooltip("Sound effect clip to play")]
public AudioClip soundClip; [SerializeField] protected AudioClip soundClip;
[Range(0,1)] [Range(0,1)]
[Tooltip("Volume level of the sound effect")] [Tooltip("Volume level of the sound effect")]
public float volume = 1; [SerializeField] protected float volume = 1;
[Tooltip("Wait until the sound has finished playing before continuing execution.")] [Tooltip("Wait until the sound has finished playing before continuing execution.")]
public bool waitUntilFinished; [SerializeField] protected bool waitUntilFinished;
public override void OnEnter() public override void OnEnter()
{ {
@ -68,5 +68,4 @@ namespace Fungus
return new Color32(242, 209, 176, 255); return new Color32(242, 209, 176, 255);
} }
} }
} }

52
Assets/Fungus/Audio/Scripts/Commands/PlayUsfxrSound.cs

@ -1,13 +1,15 @@
/** // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
namespace Fungus { using System;
using System; using UnityEngine;
using UnityEngine; using UnityEngine.Serialization;
using UnityEngine.Serialization;
namespace Fungus
{
/// <summary>
/// Plays a usfxr synth sound. Use the usfxr editor [Tools > Fungus > Utilities > Generate usfxr Sound Effects] to create the SettingsString. Set a ParentTransform if using positional sound. See https://github.com/zeh/usfxr for more information about usfxr.
/// </summary>
[CommandInfo("Audio", [CommandInfo("Audio",
"Play Usfxr Sound", "Play Usfxr Sound",
"Plays a usfxr synth sound. Use the usfxr editor [Tools > Fungus > Utilities > Generate usfxr Sound Effects] to create the SettingsString. Set a ParentTransform if using positional sound. See https://github.com/zeh/usfxr for more information about usfxr.")] "Plays a usfxr synth sound. Use the usfxr editor [Tools > Fungus > Utilities > Generate usfxr Sound Effects] to create the SettingsString. Set a ParentTransform if using positional sound. See https://github.com/zeh/usfxr for more information about usfxr.")]
@ -15,31 +17,35 @@
[ExecuteInEditMode] [ExecuteInEditMode]
public class PlayUsfxrSound : Command public class PlayUsfxrSound : Command
{ {
protected SfxrSynth _synth = new SfxrSynth();
[Tooltip("Transform to use for positional audio")] [Tooltip("Transform to use for positional audio")]
public Transform ParentTransform = null; [SerializeField] protected Transform ParentTransform = null;
[Tooltip("Settings string which describes the audio")] [Tooltip("Settings string which describes the audio")]
public StringDataMulti _SettingsString = new StringDataMulti(""); [SerializeField] protected StringDataMulti _SettingsString = new StringDataMulti("");
[Tooltip("Time to wait before executing the next command")] [Tooltip("Time to wait before executing the next command")]
public float waitDuration = 0; [SerializeField] protected float waitDuration = 0;
protected SfxrSynth _synth = new SfxrSynth();
//Call this if the settings have changed //Call this if the settings have changed
protected void UpdateCache() { protected void UpdateCache()
if (_SettingsString.Value != null) { {
if (_SettingsString.Value != null)
{
_synth.parameters.SetSettingsString(_SettingsString.Value); _synth.parameters.SetSettingsString(_SettingsString.Value);
_synth.CacheSound(); _synth.CacheSound();
} }
} }
public void Awake() { public void Awake()
{
//Always build the cache on awake //Always build the cache on awake
UpdateCache(); UpdateCache();
} }
public override void OnEnter() { public override void OnEnter()
{
_synth.SetParentTransform(ParentTransform); _synth.SetParentTransform(ParentTransform);
_synth.Play(); _synth.Play();
if (waitDuration == 0f) if (waitDuration == 0f)
@ -57,17 +63,21 @@
Continue(); Continue();
} }
public override string GetSummary() { public override string GetSummary()
if (String.IsNullOrEmpty(_SettingsString.Value)) { {
if (String.IsNullOrEmpty(_SettingsString.Value))
{
return "Settings String hasn't been set!"; return "Settings String hasn't been set!";
} }
if (ParentTransform != null) { if (ParentTransform != null)
{
return "" + ParentTransform.name + ": " + _SettingsString.Value; return "" + ParentTransform.name + ": " + _SettingsString.Value;
} }
return "Camera.main: " + _SettingsString.Value; return "Camera.main: " + _SettingsString.Value;
} }
public override Color GetButtonColor() { public override Color GetButtonColor()
{
return new Color32(128, 200, 200, 255); return new Color32(128, 200, 200, 255);
} }

17
Assets/Fungus/Audio/Scripts/Commands/SetAudioPitch.cs

@ -1,13 +1,13 @@
/** // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
using UnityEngine; using UnityEngine;
using System.Collections;
namespace Fungus namespace Fungus
{ {
/// <summary>
/// Sets the global pitch level for audio played with Play Music and Play Sound commands.
/// </summary>
[CommandInfo("Audio", [CommandInfo("Audio",
"Set Audio Pitch", "Set Audio Pitch",
"Sets the global pitch level for audio played with Play Music and Play Sound commands.")] "Sets the global pitch level for audio played with Play Music and Play Sound commands.")]
@ -16,14 +16,14 @@ namespace Fungus
{ {
[Range(0,1)] [Range(0,1)]
[Tooltip("Global pitch level for audio played using the Play Music and Play Sound commands")] [Tooltip("Global pitch level for audio played using the Play Music and Play Sound commands")]
public float pitch = 1; [SerializeField] protected float pitch = 1;
[Range(0,30)] [Range(0,30)]
[Tooltip("Time to fade between current pitch level and target pitch level.")] [Tooltip("Time to fade between current pitch level and target pitch level.")]
public float fadeDuration; [SerializeField] protected float fadeDuration;
[Tooltip("Wait until the pitch change has finished before executing next command")] [Tooltip("Wait until the pitch change has finished before executing next command")]
public bool waitUntilFinished = true; [SerializeField] protected bool waitUntilFinished = true;
public override void OnEnter() public override void OnEnter()
{ {
@ -56,5 +56,4 @@ namespace Fungus
return new Color32(242, 209, 176, 255); return new Color32(242, 209, 176, 255);
} }
} }
} }

17
Assets/Fungus/Audio/Scripts/Commands/SetAudioVolume.cs

@ -1,13 +1,13 @@
/** // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
using UnityEngine; using UnityEngine;
using System.Collections;
namespace Fungus namespace Fungus
{ {
/// <summary>
/// Sets the global volume level for audio played with Play Music and Play Sound commands.
/// </summary>
[CommandInfo("Audio", [CommandInfo("Audio",
"Set Audio Volume", "Set Audio Volume",
"Sets the global volume level for audio played with Play Music and Play Sound commands.")] "Sets the global volume level for audio played with Play Music and Play Sound commands.")]
@ -16,14 +16,14 @@ namespace Fungus
{ {
[Range(0,1)] [Range(0,1)]
[Tooltip("Global volume level for audio played using Play Music and Play Sound")] [Tooltip("Global volume level for audio played using Play Music and Play Sound")]
public float volume = 1f; [SerializeField] protected float volume = 1f;
[Range(0,30)] [Range(0,30)]
[Tooltip("Time to fade between current volume level and target volume level.")] [Tooltip("Time to fade between current volume level and target volume level.")]
public float fadeDuration = 1f; [SerializeField] protected float fadeDuration = 1f;
[Tooltip("Wait until the volume fade has completed before continuing.")] [Tooltip("Wait until the volume fade has completed before continuing.")]
public bool waitUntilFinished = true; [SerializeField] protected bool waitUntilFinished = true;
public override void OnEnter() public override void OnEnter()
{ {
@ -54,5 +54,4 @@ namespace Fungus
return new Color32(242, 209, 176, 255); return new Color32(242, 209, 176, 255);
} }
} }
} }

11
Assets/Fungus/Audio/Scripts/Commands/StopMusic.cs

@ -1,13 +1,13 @@
/** // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
using UnityEngine; using UnityEngine;
using System.Collections;
namespace Fungus namespace Fungus
{ {
/// <summary>
/// Stops the currently playing game music.
/// </summary>
[CommandInfo("Audio", [CommandInfo("Audio",
"Stop Music", "Stop Music",
"Stops the currently playing game music.")] "Stops the currently playing game music.")]
@ -30,5 +30,4 @@ namespace Fungus
return new Color32(242, 209, 176, 255); return new Color32(242, 209, 176, 255);
} }
} }
} }

76
Assets/Fungus/Audio/Scripts/MusicController.cs

@ -1,27 +1,22 @@
/** // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
using UnityEngine; using UnityEngine;
using System.Collections;
namespace Fungus namespace Fungus
{ {
/** /// <summary>
* Singleton music manager component. /// Singleton music manager component.
* Provides basic music and sound effect functionality. /// Provides basic music and sound effect functionality.
* Music playback persists across scene loads. /// Music playback persists across scene loads.
*/ /// </summary>
[RequireComponent(typeof(AudioSource))] [RequireComponent(typeof(AudioSource))]
public class MusicController : MonoBehaviour public class MusicController : MonoBehaviour
{ {
static MusicController instance; static MusicController instance;
/** // Returns the MusicController singleton instance.
* Returns the MusicController singleton instance. // Will create a MusicController game object if none currently exists.
* Will create a MusicController game object if none currently exists.
*/
static public MusicController GetInstance() static public MusicController GetInstance()
{ {
if (instance == null) if (instance == null)
@ -40,12 +35,10 @@ namespace Fungus
GetComponent<AudioSource>().loop = true; GetComponent<AudioSource>().loop = true;
} }
/** /// <summary>
* Plays game music using an audio clip. /// // Plays game music using an audio clip.
* One music clip may be played at a time. /// One music clip may be played at a time.
* @param musicClip The music clip to play /// </summary>
* @param atTime Time in the music clip to start at
*/
public void PlayMusic(AudioClip musicClip, bool loop, float fadeDuration, float atTime) public void PlayMusic(AudioClip musicClip, bool loop, float fadeDuration, float atTime)
{ {
AudioSource audioSource = GetComponent<AudioSource>(); AudioSource audioSource = GetComponent<AudioSource>();
@ -79,21 +72,21 @@ namespace Fungus
}); });
} }
} }
/** /// <summary>
* Stops playing game music. /// Stops playing game music.
*/ /// </summary>
public virtual void StopMusic() public virtual void StopMusic()
{ {
GetComponent<AudioSource>().Stop(); GetComponent<AudioSource>().Stop();
} }
/** /// <summary>
* Fades the game music volume to required level over a period of time. /// Fades the game music volume to required level over a period of time.
* @param volume The new music volume value [0..1] /// </summary>
* @param duration The length of time in seconds needed to complete the volume change. /// <param name="volume">The new music volume value [0..1]</param>
* @param onComplete Delegate function to call when fade completes. /// <param name="duration">The length of time in seconds needed to complete the volume change.</param>
*/ /// <param name="onComplete">Delegate function to call when fade completes.</param>
public virtual void SetAudioVolume(float volume, float duration, System.Action onComplete) public virtual void SetAudioVolume(float volume, float duration, System.Action onComplete)
{ {
AudioSource audio = GetComponent<AudioSource>(); AudioSource audio = GetComponent<AudioSource>();
@ -117,12 +110,12 @@ namespace Fungus
}); });
} }
/** /// <summary>
* Shifts the game music pitch to required value over a period of time. /// Shifts the game music pitch to required value over a period of time.
* @param volume The new music pitch value /// </summary>
* @param duration The length of time in seconds needed to complete the pitch change. /// <param name="pitch">The new music pitch value.</param>
* @param onComplete A delegate method to call when the pitch shift has completed. /// <param name="duration">The length of time in seconds needed to complete the pitch change.</param>
*/ /// <param name="onComplete">A delegate method to call when the pitch shift has completed.</param>
public virtual void SetAudioPitch(float pitch, float duration, System.Action onComplete) public virtual void SetAudioPitch(float pitch, float duration, System.Action onComplete)
{ {
AudioSource audio = GetComponent<AudioSource>(); AudioSource audio = GetComponent<AudioSource>();
@ -150,12 +143,11 @@ namespace Fungus
}); });
} }
/** /// <summary>
* Plays a sound effect once, at the specified volume. /// Plays a sound effect once, at the specified volume.
* Multiple sound effects can be played at the same time. /// </summary>
* @param soundClip The sound effect clip to play /// <param name="soundClip">The sound effect clip to play.</param>
* @param volume The volume level of the sound effect /// <param name="volume">The volume level of the sound effect.</param>
*/
public virtual void PlaySound(AudioClip soundClip, float volume) public virtual void PlaySound(AudioClip soundClip, float volume)
{ {
GetComponent<AudioSource>().PlayOneShot(soundClip, volume); GetComponent<AudioSource>().PlayOneShot(soundClip, volume);

9
Assets/Fungus/Camera/Editor/CameraMenuItems.cs

@ -1,15 +1,11 @@
/** // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
using UnityEngine; using UnityEngine;
using UnityEditor; using UnityEditor;
using System.Collections;
namespace Fungus namespace Fungus
{ {
public class CameraMenuItems public class CameraMenuItems
{ {
[MenuItem("Tools/Fungus/Create/View", false, 100)] [MenuItem("Tools/Fungus/Create/View", false, 100)]
@ -18,5 +14,4 @@ namespace Fungus
FlowchartMenuItems.SpawnPrefab("View"); FlowchartMenuItems.SpawnPrefab("View");
} }
} }
} }

24
Assets/Fungus/Camera/Editor/ViewEditor.cs

@ -1,16 +1,11 @@
/** // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
using UnityEditor; using UnityEditor;
using UnityEngine; using UnityEngine;
using System.Collections;
using System.Collections.Generic;
namespace Fungus namespace Fungus
{ {
[CanEditMultipleObjects] [CanEditMultipleObjects]
[CustomEditor (typeof(View))] [CustomEditor (typeof(View))]
public class ViewEditor : Editor public class ViewEditor : Editor
@ -154,7 +149,7 @@ namespace Fungus
if (newPos != handles[i]) if (newPos != handles[i])
{ {
Undo.RecordObject(view, "Set View Size"); Undo.RecordObject(view, "Set View Size");
view.viewSize = (newPos - pos).magnitude; view.ViewSize = (newPos - pos).magnitude;
EditorUtility.SetDirty(view); EditorUtility.SetDirty(view);
break; break;
} }
@ -164,8 +159,8 @@ namespace Fungus
public static void DrawView(View view, bool drawInterior) public static void DrawView(View view, bool drawInterior)
{ {
float height = CalculateLocalViewSize(view); float height = CalculateLocalViewSize(view);
float widthA = height * (view.primaryAspectRatio.x / view.primaryAspectRatio.y); float widthA = height * (view.PrimaryAspectRatio.x / view.PrimaryAspectRatio.y);
float widthB = height * (view.secondaryAspectRatio.x / view.secondaryAspectRatio.y); float widthB = height * (view.SecondaryAspectRatio.x / view.SecondaryAspectRatio.y);
Color transparent = new Color(1,1,1,0f); Color transparent = new Color(1,1,1,0f);
Color fill = viewColor; Color fill = viewColor;
@ -176,11 +171,11 @@ namespace Fungus
Flowchart flowchart = FlowchartWindow.GetFlowchart(); Flowchart flowchart = FlowchartWindow.GetFlowchart();
if (flowchart != null) if (flowchart != null)
{ {
foreach (Command command in flowchart.selectedCommands) foreach (Command command in flowchart.SelectedCommands)
{ {
MoveToView moveToViewCommand = command as MoveToView; MoveToView moveToViewCommand = command as MoveToView;
if (moveToViewCommand != null && if (moveToViewCommand != null &&
moveToViewCommand.targetView == view) moveToViewCommand.TargetView == view)
{ {
highlight = true; highlight = true;
} }
@ -188,7 +183,7 @@ namespace Fungus
{ {
FadeToView fadeToViewCommand = command as FadeToView; FadeToView fadeToViewCommand = command as FadeToView;
if (fadeToViewCommand != null && if (fadeToViewCommand != null &&
fadeToViewCommand.targetView == view) fadeToViewCommand.TargetView == view)
{ {
highlight = true; highlight = true;
} }
@ -260,8 +255,7 @@ namespace Fungus
// Kinda expensive, but accurate and only called in editor. // Kinda expensive, but accurate and only called in editor.
static float CalculateLocalViewSize(View view) static float CalculateLocalViewSize(View view)
{ {
return view.transform.InverseTransformPoint(view.transform.position + new Vector3(0, view.viewSize, 0)).magnitude; return view.transform.InverseTransformPoint(view.transform.position + new Vector3(0, view.ViewSize, 0)).magnitude;
} }
} }
} }

158
Assets/Fungus/Camera/Scripts/CameraController.cs

@ -1,7 +1,5 @@
/** // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
using UnityEngine; using UnityEngine;
using System; using System;
@ -11,50 +9,36 @@ using Fungus;
namespace Fungus namespace Fungus
{ {
/** /// <summary>
* Controller for main camera. /// Controller for main camera.Supports several types of camera transition including snap, pan & fade.
* Supports several types of camera transition including snap, pan & fade. /// </summary>
*/
public class CameraController : MonoBehaviour public class CameraController : MonoBehaviour
{ {
/** [Tooltip("Full screen texture used for screen fade effect.")]
* Full screen texture used for screen fade effect. [SerializeField] protected Texture2D screenFadeTexture;
*/ public Texture2D ScreenFadeTexture { set { screenFadeTexture = value; } }
public Texture2D screenFadeTexture;
[Tooltip("Icon to display when swipe pan mode is active.")]
/** [SerializeField] protected Texture2D swipePanIcon;
* Icon to display when swipe pan mode is active.
*/ [Tooltip("Position of continue and swipe icons in normalized screen space coords. (0,0) = top left, (1,1) = bottom right")]
public Texture2D swipePanIcon; [SerializeField] protected Vector2 swipeIconPosition = new Vector2(1,0);
/** [Tooltip("Set the camera z coordinate to a fixed value every frame.")]
* Position of continue and swipe icons in normalized screen space coords. [SerializeField] protected bool setCameraZ = true;
* (0,0) = top left, (1,1) = bottom right
*/ [Tooltip("Fixed Z coordinate of main camera.")]
public Vector2 swipeIconPosition = new Vector2(1,0); [SerializeField] protected float cameraZ = -10f;
/** [Tooltip("Camera to use when in swipe mode")]
* Set the camera z coordinate to a fixed value every frame. [SerializeField] protected Camera swipeCamera;
*/
public bool setCameraZ = true;
/**
* Fixed Z coordinate of main camera.
*/
public float cameraZ = -10f;
[HideInInspector]
public bool waiting;
protected float fadeAlpha = 0f; protected float fadeAlpha = 0f;
// Swipe panning control // Swipe panning control
[HideInInspector] protected bool swipePanActive;
public bool swipePanActive;
public Camera swipeCamera;
[HideInInspector] protected float swipeSpeedMultiplier = 1f;
public float swipeSpeedMultiplier = 1f;
protected View swipePanViewA; protected View swipePanViewA;
protected View swipePanViewB; protected View swipePanViewB;
protected Vector3 previousMousePos; protected Vector3 previousMousePos;
@ -70,10 +54,10 @@ namespace Fungus
protected static CameraController instance; protected static CameraController instance;
/** /// <summary>
* Returns the CameraController singleton instance. /// Returns the CameraController singleton instance.
* Will create a CameraController game object if none currently exists. /// Will create a CameraController game object if none currently exists.
*/ /// </summary>
static public CameraController GetInstance() static public CameraController GetInstance()
{ {
if (instance == null) if (instance == null)
@ -132,18 +116,18 @@ namespace Fungus
GUI.DrawTexture(new Rect(0, 0, Screen.width, Screen.height), screenFadeTexture); GUI.DrawTexture(new Rect(0, 0, Screen.width, Screen.height), screenFadeTexture);
} }
} }
/** /// <summary>
* Perform a fullscreen fade over a duration. /// Perform a fullscreen fade over a duration.
*/ /// </summary>
public virtual void Fade(float targetAlpha, float fadeDuration, Action fadeAction) public virtual void Fade(float targetAlpha, float fadeDuration, Action fadeAction)
{ {
StartCoroutine(FadeInternal(targetAlpha, fadeDuration, fadeAction)); StartCoroutine(FadeInternal(targetAlpha, fadeDuration, fadeAction));
} }
/** /// <summary>
* Fade out, move camera to view and then fade back in. /// Fade out, move camera to view and then fade back in.
*/ /// </summary>
public virtual void FadeToView(Camera camera, View view, float fadeDuration, bool fadeOut, Action fadeAction) public virtual void FadeToView(Camera camera, View view, float fadeDuration, bool fadeOut, Action fadeAction)
{ {
swipePanActive = false; swipePanActive = false;
@ -167,7 +151,7 @@ namespace Fungus
Fade(1f, outDuration, delegate { Fade(1f, outDuration, delegate {
// Snap to new view // Snap to new view
PanToPosition(camera, view.transform.position, view.transform.rotation, view.viewSize, 0f, null); PanToPosition(camera, view.transform.position, view.transform.rotation, view.ViewSize, 0f, null);
// Fade in // Fade in
Fade(0f, inDuration, delegate { Fade(0f, inDuration, delegate {
@ -210,11 +194,10 @@ namespace Fungus
fadeAction(); fadeAction();
} }
} }
/** /// <summary>
* Positions camera so sprite is centered and fills the screen. /// Positions camera so sprite is centered and fills the screen.
* @param spriteRenderer The sprite to center the camera on /// </summary>
*/
public virtual void CenterOnSprite(Camera camera, SpriteRenderer spriteRenderer) public virtual void CenterOnSprite(Camera camera, SpriteRenderer spriteRenderer)
{ {
if (camera == null) if (camera == null)
@ -244,12 +227,12 @@ namespace Fungus
public virtual void PanToView(Camera camera, View view, float duration, Action arriveAction) public virtual void PanToView(Camera camera, View view, float duration, Action arriveAction)
{ {
PanToPosition(camera, view.transform.position, view.transform.rotation, view.viewSize, duration, arriveAction); PanToPosition(camera, view.transform.position, view.transform.rotation, view.ViewSize, duration, arriveAction);
} }
/** /// <summary>
* Moves camera from current position to a target position over a period of time. /// Moves camera from current position to a target position over a period of time.
*/ /// </summary>
public virtual void PanToPosition(Camera camera, Vector3 targetPosition, Quaternion targetRotation, float targetSize, float duration, Action arriveAction) public virtual void PanToPosition(Camera camera, Vector3 targetPosition, Quaternion targetRotation, float targetSize, float duration, Action arriveAction)
{ {
if (camera == null) if (camera == null)
@ -282,10 +265,10 @@ namespace Fungus
StartCoroutine(PanInternal(camera, targetPosition, targetRotation, targetSize, duration, arriveAction)); StartCoroutine(PanInternal(camera, targetPosition, targetRotation, targetSize, duration, arriveAction));
} }
} }
/** /// <summary>
* Stores the current camera view using a name. /// Stores the current camera view using a name.
*/ /// </summary>
public virtual void StoreView(Camera camera, string viewName) public virtual void StoreView(Camera camera, string viewName)
{ {
if (camera != null) if (camera != null)
@ -300,10 +283,10 @@ namespace Fungus
currentView.cameraSize = camera.orthographicSize; currentView.cameraSize = camera.orthographicSize;
storedViews[viewName] = currentView; storedViews[viewName] = currentView;
} }
/** /// <summary>
* Moves the camera to a previously stored camera view over a period of time. /// Moves the camera to a previously stored camera view over a period of time.
*/ /// </summary>
public virtual void PanToStoredView(Camera camera, string viewName, float duration, Action arriveAction) public virtual void PanToStoredView(Camera camera, string viewName, float duration, Action arriveAction)
{ {
if (camera == null) if (camera == null)
@ -395,10 +378,10 @@ namespace Fungus
yield return null; yield return null;
} }
} }
/** /// <summary>
* Moves camera smoothly through a sequence of Views over a period of time /// Moves camera smoothly through a sequence of Views over a period of time.
*/ /// </summary>
public virtual void PanToPath(Camera camera, View[] viewList, float duration, Action arriveAction) public virtual void PanToPath(Camera camera, View[] viewList, float duration, Action arriveAction)
{ {
if (camera == null) if (camera == null)
@ -424,7 +407,7 @@ namespace Fungus
Vector3 viewPos = new Vector3(view.transform.position.x, Vector3 viewPos = new Vector3(view.transform.position.x,
view.transform.position.y, view.transform.position.y,
view.viewSize); view.ViewSize);
pathList.Add(viewPos); pathList.Add(viewPos);
} }
@ -462,11 +445,10 @@ namespace Fungus
arriveAction(); arriveAction();
} }
} }
/** /// <summary>
* Activates swipe panning mode. /// Activates swipe panning mode. The player can pan the camera within the area between viewA & viewB.
* The player can pan the camera within the area between viewA & viewB. /// </summary>
*/
public virtual void StartSwipePan(Camera camera, View viewA, View viewB, float duration, float speedMultiplier, Action arriveAction) public virtual void StartSwipePan(Camera camera, View viewA, View viewB, float duration, float speedMultiplier, Action arriveAction)
{ {
if (camera == null) if (camera == null)
@ -495,10 +477,10 @@ namespace Fungus
} }
}); });
} }
/** /// <summary>
* Deactivates swipe panning mode. /// Deactivates swipe panning mode.
*/ /// </summary>
public virtual void StopSwipePan() public virtual void StopSwipePan()
{ {
swipePanActive = false; swipePanActive = false;
@ -599,7 +581,7 @@ namespace Fungus
float t = Vector3.Dot(toViewB, localPos); float t = Vector3.Dot(toViewB, localPos);
t = Mathf.Clamp01(t); // Not really necessary but no harm t = Mathf.Clamp01(t); // Not really necessary but no harm
float cameraSize = Mathf.Lerp(viewA.viewSize, viewB.viewSize, t); float cameraSize = Mathf.Lerp(viewA.ViewSize, viewB.ViewSize, t);
return cameraSize; return cameraSize;
} }

35
Assets/Fungus/Camera/Scripts/Commands/FadeScreen.cs

@ -1,14 +1,14 @@
/** // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
using UnityEngine; using UnityEngine;
using System;
using System.Collections;
namespace Fungus namespace Fungus
{ {
/// <summary>
/// Draws a fullscreen texture over the scene to give a fade effect. Setting Target Alpha to 1 will obscure the screen, alpha 0 will reveal the screen.
/// If no Fade Texture is provided then a default flat color texture is used.
/// </summary>
[CommandInfo("Camera", [CommandInfo("Camera",
"Fade Screen", "Fade Screen",
"Draws a fullscreen texture over the scene to give a fade effect. Setting Target Alpha to 1 will obscure the screen, alpha 0 will reveal the screen. " + "Draws a fullscreen texture over the scene to give a fade effect. Setting Target Alpha to 1 will obscure the screen, alpha 0 will reveal the screen. " +
@ -17,42 +17,36 @@ namespace Fungus
public class FadeScreen : Command public class FadeScreen : Command
{ {
[Tooltip("Time for fade effect to complete")] [Tooltip("Time for fade effect to complete")]
public float duration = 1f; [SerializeField] protected float duration = 1f;
[Tooltip("Current target alpha transparency value. The fade gradually adjusts the alpha to approach this target value.")] [Tooltip("Current target alpha transparency value. The fade gradually adjusts the alpha to approach this target value.")]
public float targetAlpha = 1f; [SerializeField] protected float targetAlpha = 1f;
[Tooltip("Wait until the fade has finished before executing next command")] [Tooltip("Wait until the fade has finished before executing next command")]
public bool waitUntilFinished = true; [SerializeField] protected bool waitUntilFinished = true;
[Tooltip("Color to render fullscreen fade texture with when screen is obscured.")] [Tooltip("Color to render fullscreen fade texture with when screen is obscured.")]
public Color fadeColor = Color.black; [SerializeField] protected Color fadeColor = Color.black;
[Tooltip("Optional texture to use when rendering the fullscreen fade effect.")] [Tooltip("Optional texture to use when rendering the fullscreen fade effect.")]
public Texture2D fadeTexture; [SerializeField] protected Texture2D fadeTexture;
public override void OnEnter() public override void OnEnter()
{ {
CameraController cameraController = CameraController.GetInstance(); CameraController cameraController = CameraController.GetInstance();
if (waitUntilFinished)
{
cameraController.waiting = true;
}
if (fadeTexture) if (fadeTexture)
{ {
cameraController.screenFadeTexture = fadeTexture; cameraController.ScreenFadeTexture = fadeTexture;
} }
else else
{ {
cameraController.screenFadeTexture = CameraController.CreateColorTexture(fadeColor, 32, 32); cameraController.ScreenFadeTexture = CameraController.CreateColorTexture(fadeColor, 32, 32);
} }
cameraController.Fade(targetAlpha, duration, delegate { cameraController.Fade(targetAlpha, duration, delegate {
if (waitUntilFinished) if (waitUntilFinished)
{ {
cameraController.waiting = false;
Continue(); Continue();
} }
}); });
@ -72,6 +66,5 @@ namespace Fungus
{ {
return new Color32(216, 228, 170, 255); return new Color32(216, 228, 170, 255);
} }
} }
} }

37
Assets/Fungus/Camera/Scripts/Commands/FadeToView.cs

@ -1,14 +1,13 @@
/** // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
using UnityEngine; using UnityEngine;
using System;
using System.Collections;
namespace Fungus namespace Fungus
{ {
/// <summary>
/// Fades the camera out and in again at a position specified by a View object.
/// </summary>
[CommandInfo("Camera", [CommandInfo("Camera",
"Fade To View", "Fade To View",
"Fades the camera out and in again at a position specified by a View object.")] "Fades the camera out and in again at a position specified by a View object.")]
@ -16,25 +15,26 @@ namespace Fungus
public class FadeToView : Command public class FadeToView : Command
{ {
[Tooltip("Time for fade effect to complete")] [Tooltip("Time for fade effect to complete")]
public float duration = 1f; [SerializeField] protected float duration = 1f;
[Tooltip("Fade from fully visible to opaque at start of fade")] [Tooltip("Fade from fully visible to opaque at start of fade")]
public bool fadeOut = true; [SerializeField] protected bool fadeOut = true;
[Tooltip("View to transition to when Fade is complete")] [Tooltip("View to transition to when Fade is complete")]
public View targetView; [SerializeField] protected View targetView;
public View TargetView { get { return targetView; } }
[Tooltip("Wait until the fade has finished before executing next command")] [Tooltip("Wait until the fade has finished before executing next command")]
public bool waitUntilFinished = true; [SerializeField] protected bool waitUntilFinished = true;
[Tooltip("Color to render fullscreen fade texture with when screen is obscured.")] [Tooltip("Color to render fullscreen fade texture with when screen is obscured.")]
public Color fadeColor = Color.black; [SerializeField] protected Color fadeColor = Color.black;
[Tooltip("Optional texture to use when rendering the fullscreen fade effect.")] [Tooltip("Optional texture to use when rendering the fullscreen fade effect.")]
public Texture2D fadeTexture; [SerializeField] protected Texture2D fadeTexture;
[Tooltip("Camera to use for the fade. Will use main camera if set to none.")] [Tooltip("Camera to use for the fade. Will use main camera if set to none.")]
public Camera targetCamera; [SerializeField] protected Camera targetCamera;
protected virtual void AcquireCamera() protected virtual void AcquireCamera()
{ {
@ -67,24 +67,18 @@ namespace Fungus
CameraController cameraController = CameraController.GetInstance(); CameraController cameraController = CameraController.GetInstance();
if (waitUntilFinished)
{
cameraController.waiting = true;
}
if (fadeTexture) if (fadeTexture)
{ {
cameraController.screenFadeTexture = fadeTexture; cameraController.ScreenFadeTexture = fadeTexture;
} }
else else
{ {
cameraController.screenFadeTexture = CameraController.CreateColorTexture(fadeColor, 32, 32); cameraController.ScreenFadeTexture = CameraController.CreateColorTexture(fadeColor, 32, 32);
} }
cameraController.FadeToView(targetCamera, targetView, duration, fadeOut, delegate { cameraController.FadeToView(targetCamera, targetView, duration, fadeOut, delegate {
if (waitUntilFinished) if (waitUntilFinished)
{ {
cameraController.waiting = false;
Continue(); Continue();
} }
}); });
@ -117,5 +111,4 @@ namespace Fungus
return new Color32(216, 228, 170, 255); return new Color32(216, 228, 170, 255);
} }
} }
} }

14
Assets/Fungus/Camera/Scripts/Commands/Fullscreen.cs

@ -1,14 +1,13 @@
/** // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
using UnityEngine; using UnityEngine;
using System;
using System.Collections;
namespace Fungus namespace Fungus
{ {
/// <summary>
/// Sets the application to fullscreen, windowed or toggles the current state.
/// </summary>
[CommandInfo("Camera", [CommandInfo("Camera",
"Fullscreen", "Fullscreen",
"Sets the application to fullscreen, windowed or toggles the current state.")] "Sets the application to fullscreen, windowed or toggles the current state.")]
@ -22,7 +21,7 @@ namespace Fungus
Windowed Windowed
} }
public FullscreenMode fullscreenMode; [SerializeField] protected FullscreenMode fullscreenMode;
public override void OnEnter() public override void OnEnter()
{ {
@ -52,5 +51,4 @@ namespace Fungus
return new Color32(216, 228, 170, 255); return new Color32(216, 228, 170, 255);
} }
} }
} }

29
Assets/Fungus/Camera/Scripts/Commands/MoveToView.cs

@ -1,14 +1,13 @@
/** // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
using UnityEngine; using UnityEngine;
using System;
using System.Collections;
namespace Fungus namespace Fungus
{ {
/// <summary>
/// Moves the camera to a location specified by a View object.
/// </summary>
[CommandInfo("Camera", [CommandInfo("Camera",
"Move To View", "Move To View",
"Moves the camera to a location specified by a View object.")] "Moves the camera to a location specified by a View object.")]
@ -16,16 +15,17 @@ namespace Fungus
public class MoveToView : Command public class MoveToView : Command
{ {
[Tooltip("Time for move effect to complete")] [Tooltip("Time for move effect to complete")]
public float duration = 1; [SerializeField] protected float duration = 1;
[Tooltip("View to transition to when move is complete")] [Tooltip("View to transition to when move is complete")]
public Fungus.View targetView; [SerializeField] protected View targetView;
public View TargetView { get { return targetView; } }
[Tooltip("Wait until the fade has finished before executing next command")] [Tooltip("Wait until the fade has finished before executing next command")]
public bool waitUntilFinished = true; [SerializeField] protected bool waitUntilFinished = true;
[Tooltip("Camera to use for the pan. Will use main camera if set to none.")] [Tooltip("Camera to use for the pan. Will use main camera if set to none.")]
public Camera targetCamera; [SerializeField] protected Camera targetCamera;
protected virtual void AcquireCamera() protected virtual void AcquireCamera()
{ {
@ -58,19 +58,13 @@ namespace Fungus
CameraController cameraController = CameraController.GetInstance(); CameraController cameraController = CameraController.GetInstance();
if (waitUntilFinished)
{
cameraController.waiting = true;
}
Vector3 targetPosition = targetView.transform.position; Vector3 targetPosition = targetView.transform.position;
Quaternion targetRotation = targetView.transform.rotation; Quaternion targetRotation = targetView.transform.rotation;
float targetSize = targetView.viewSize; float targetSize = targetView.ViewSize;
cameraController.PanToPosition(targetCamera, targetPosition, targetRotation, targetSize, duration, delegate { cameraController.PanToPosition(targetCamera, targetPosition, targetRotation, targetSize, duration, delegate {
if (waitUntilFinished) if (waitUntilFinished)
{ {
cameraController.waiting = false;
Continue(); Continue();
} }
}); });
@ -103,5 +97,4 @@ namespace Fungus
return new Color32(216, 228, 170, 255); return new Color32(216, 228, 170, 255);
} }
} }
} }

19
Assets/Fungus/Camera/Scripts/Commands/ShakeCamera.cs

@ -1,14 +1,14 @@
/** // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
using UnityEngine; using UnityEngine;
using System;
using System.Collections; using System.Collections;
namespace Fungus namespace Fungus
{ {
/// <summary>
/// Applies a camera shake effect to the main camera.
/// </summary>
[CommandInfo("Camera", [CommandInfo("Camera",
"Shake Camera", "Shake Camera",
"Applies a camera shake effect to the main camera.")] "Applies a camera shake effect to the main camera.")]
@ -16,13 +16,13 @@ namespace Fungus
public class ShakeCamera : Command public class ShakeCamera : Command
{ {
[Tooltip("Time for camera shake effect to complete")] [Tooltip("Time for camera shake effect to complete")]
public float duration = 0.5f; [SerializeField] protected float duration = 0.5f;
[Tooltip("Magnitude of shake effect in x & y axes")] [Tooltip("Magnitude of shake effect in x & y axes")]
public Vector2 amount = new Vector2(1, 1); [SerializeField] protected Vector2 amount = new Vector2(1, 1);
[Tooltip("Wait until the shake effect has finished before executing next command")] [Tooltip("Wait until the shake effect has finished before executing next command")]
public bool waitUntilFinished; [SerializeField] protected bool waitUntilFinished;
public override void OnEnter() public override void OnEnter()
{ {
@ -64,6 +64,5 @@ namespace Fungus
{ {
return new Color32(216, 228, 170, 255); return new Color32(216, 228, 170, 255);
} }
} }
} }

22
Assets/Fungus/Camera/Scripts/Commands/StartSwipe.cs

@ -1,14 +1,13 @@
/** // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
using UnityEngine; using UnityEngine;
using System;
using System.Collections;
namespace Fungus namespace Fungus
{ {
/// <summary>
/// Activates swipe panning mode where the player can pan the camera within the area between viewA & viewB.
/// </summary>
[CommandInfo("Camera", [CommandInfo("Camera",
"Start Swipe", "Start Swipe",
"Activates swipe panning mode where the player can pan the camera within the area between viewA & viewB.")] "Activates swipe panning mode where the player can pan the camera within the area between viewA & viewB.")]
@ -16,19 +15,19 @@ namespace Fungus
public class StartSwipe : Command public class StartSwipe : Command
{ {
[Tooltip("Defines one extreme of the scrollable area that the player can pan around")] [Tooltip("Defines one extreme of the scrollable area that the player can pan around")]
public View viewA; [SerializeField] protected View viewA;
[Tooltip("Defines one extreme of the scrollable area that the player can pan around")] [Tooltip("Defines one extreme of the scrollable area that the player can pan around")]
public View viewB; [SerializeField] protected View viewB;
[Tooltip("Time to move the camera to a valid starting position between the two views")] [Tooltip("Time to move the camera to a valid starting position between the two views")]
public float duration = 0.5f; [SerializeField] protected float duration = 0.5f;
[Tooltip("Multiplier factor for speed of swipe pan")] [Tooltip("Multiplier factor for speed of swipe pan")]
public float speedMultiplier = 1f; [SerializeField] protected float speedMultiplier = 1f;
[Tooltip("Camera to use for the pan. Will use main camera if set to none.")] [Tooltip("Camera to use for the pan. Will use main camera if set to none.")]
public Camera targetCamera; [SerializeField] protected Camera targetCamera;
public virtual void Start() public virtual void Start()
{ {
@ -77,5 +76,4 @@ namespace Fungus
return new Color32(216, 228, 170, 255); return new Color32(216, 228, 170, 255);
} }
} }
} }

12
Assets/Fungus/Camera/Scripts/Commands/StopSwipe.cs

@ -1,14 +1,13 @@
/** // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
using UnityEngine; using UnityEngine;
using System;
using System.Collections;
namespace Fungus namespace Fungus
{ {
/// <summary>
/// Deactivates swipe panning mode.
/// </summary>
[CommandInfo("Camera", [CommandInfo("Camera",
"Stop Swipe", "Stop Swipe",
"Deactivates swipe panning mode.")] "Deactivates swipe panning mode.")]
@ -29,5 +28,4 @@ namespace Fungus
return new Color32(216, 228, 170, 255); return new Color32(216, 228, 170, 255);
} }
} }
} }

45
Assets/Fungus/Camera/Scripts/View.cs

@ -1,40 +1,37 @@
/** // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
using UnityEngine; using UnityEngine;
using System.Collections;
namespace Fungus namespace Fungus
{ {
/** /// <summary>
* Defines a camera view point. /// Defines a camera view point.
* The position and rotation are specified using the game object's transform, so this class /// The position and rotation are specified using the game object's transform, so this class only needs to specify the ortographic view size.
* only needs to specify the ortographic view size. /// </summary>
*/
[ExecuteInEditMode] [ExecuteInEditMode]
public class View : MonoBehaviour public class View : MonoBehaviour
{ {
/** /// <summary>
* Orthographic size of the camera view in world units. /// Orthographic size of the camera view in world units.
*/ /// </summary>
[Tooltip("Orthographic size of the camera view in world units.")] [Tooltip("Orthographic size of the camera view in world units.")]
public float viewSize = 0.5f; [SerializeField] protected float viewSize = 0.5f;
public float ViewSize { get { return viewSize; } set { viewSize = value; } }
/** /// <summary>
* Aspect ratio of the primary view rectangle. /// Aspect ratio of the primary view rectangle. e.g. a 4:3 aspect ratio = 1.333.
* e.g. a 4:3 aspect ratio = 1.333 /// </summary>
*/
[Tooltip("Aspect ratio of the primary view rectangle. (e.g. 4:3 aspect ratio = 1.333)")] [Tooltip("Aspect ratio of the primary view rectangle. (e.g. 4:3 aspect ratio = 1.333)")]
public Vector2 primaryAspectRatio = new Vector2(4, 3); [SerializeField] protected Vector2 primaryAspectRatio = new Vector2(4, 3);
public Vector2 PrimaryAspectRatio { get { return primaryAspectRatio; } set { primaryAspectRatio = value; } }
/** /// <summary>
* Aspect ratio of the secondary view rectangle. /// Aspect ratio of the secondary view rectangle. e.g. a 2:1 aspect ratio = 2/1 = 2.0.
* e.g. a 2:1 aspect ratio = 2/1 = 2.0 /// </summary>
*/
[Tooltip("Aspect ratio of the secondary view rectangle. (e.g. 2:1 aspect ratio = 2.0)")] [Tooltip("Aspect ratio of the secondary view rectangle. (e.g. 2:1 aspect ratio = 2.0)")]
public Vector2 secondaryAspectRatio = new Vector2(2, 1); [SerializeField] protected Vector2 secondaryAspectRatio = new Vector2(2, 1);
public Vector2 SecondaryAspectRatio { get { return secondaryAspectRatio; } set { secondaryAspectRatio = value; } }
protected virtual void Update() protected virtual void Update()
{ {

22
Assets/Fungus/Flowchart/Editor/AssetModProcessor.cs

@ -1,20 +1,13 @@
/** // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
using UnityEngine;
using UnityEditor;
using System;
using System.IO; using System.IO;
using System.Collections;
using System.Collections.Generic;
namespace Fungus namespace Fungus
{ {
/** /// <summary>
* Prevents saving of selected blocks and commands to avoid version control conflicts /// Prevents saving of selected blocks and commands to avoid version control conflicts.
*/ /// </summary>
public class AssetModProcessor : UnityEditor.AssetModificationProcessor public class AssetModProcessor : UnityEditor.AssetModificationProcessor
{ {
public static string[] OnWillSaveAssets(string[] paths) public static string[] OnWillSaveAssets(string[] paths)
@ -38,15 +31,14 @@ namespace Fungus
Flowchart[] flowcharts = UnityEngine.Object.FindObjectsOfType<Flowchart>(); Flowchart[] flowcharts = UnityEngine.Object.FindObjectsOfType<Flowchart>();
foreach (Flowchart f in flowcharts) foreach (Flowchart f in flowcharts)
{ {
if (!f.saveSelection) if (!f.SaveSelection)
{ {
f.selectedBlock = null; f.SelectedBlock = null;
f.ClearSelectedCommands(); f.ClearSelectedCommands();
} }
} }
return paths; return paths;
} }
} }
} }

151
Assets/Fungus/Flowchart/Editor/BlockEditor.cs

@ -1,7 +1,5 @@
/** // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
using UnityEditor; using UnityEditor;
using UnityEditorInternal; using UnityEditorInternal;
@ -17,7 +15,6 @@ using System.Reflection;
namespace Fungus namespace Fungus
{ {
[CustomEditor (typeof(Block))] [CustomEditor (typeof(Block))]
public class BlockEditor : Editor public class BlockEditor : Editor
{ {
@ -64,7 +61,7 @@ namespace Fungus
// Ensure block name is unique for this Flowchart // Ensure block name is unique for this Flowchart
Block block = target as Block; Block block = target as Block;
string uniqueName = flowchart.GetUniqueBlockKey(blockNameProperty.stringValue, block); string uniqueName = flowchart.GetUniqueBlockKey(blockNameProperty.stringValue, block);
if (uniqueName != block.blockName) if (uniqueName != block.BlockName)
{ {
blockNameProperty.stringValue = uniqueName; blockNameProperty.stringValue = uniqueName;
} }
@ -96,7 +93,7 @@ namespace Fungus
SerializedProperty commandListProperty = serializedObject.FindProperty("commandList"); SerializedProperty commandListProperty = serializedObject.FindProperty("commandList");
if (block == flowchart.selectedBlock) if (block == flowchart.SelectedBlock)
{ {
SerializedProperty descriptionProp = serializedObject.FindProperty("description"); SerializedProperty descriptionProp = serializedObject.FindProperty("description");
EditorGUILayout.PropertyField(descriptionProp); EditorGUILayout.PropertyField(descriptionProp);
@ -106,22 +103,22 @@ namespace Fungus
block.UpdateIndentLevels(); block.UpdateIndentLevels();
// Make sure each command has a reference to its parent block // Make sure each command has a reference to its parent block
foreach (Command command in block.commandList) foreach (Command command in block.CommandList)
{ {
if (command == null) // Will be deleted from the list later on if (command == null) // Will be deleted from the list later on
{ {
continue; continue;
} }
command.parentBlock = block; command.ParentBlock = block;
} }
ReorderableListGUI.Title("Commands"); ReorderableListGUI.Title("Commands");
CommandListAdaptor adaptor = new CommandListAdaptor(commandListProperty, 0); CommandListAdaptor adaptor = new CommandListAdaptor(commandListProperty, 0);
adaptor.nodeRect = block.nodeRect; adaptor.nodeRect = block._NodeRect;
ReorderableListFlags flags = ReorderableListFlags.HideAddButton | ReorderableListFlags.HideRemoveButtons | ReorderableListFlags.DisableContextMenu; ReorderableListFlags flags = ReorderableListFlags.HideAddButton | ReorderableListFlags.HideRemoveButtons | ReorderableListFlags.DisableContextMenu;
if (block.commandList.Count == 0) if (block.CommandList.Count == 0)
{ {
EditorGUILayout.HelpBox("Press the + button below to add a command to the list.", MessageType.Info); EditorGUILayout.HelpBox("Press the + button below to add a command to the list.", MessageType.Info);
} }
@ -146,7 +143,7 @@ namespace Fungus
// Copy keyboard shortcut // Copy keyboard shortcut
if (e.type == EventType.ValidateCommand && e.commandName == "Copy") if (e.type == EventType.ValidateCommand && e.commandName == "Copy")
{ {
if (flowchart.selectedCommands.Count > 0) if (flowchart.SelectedCommands.Count > 0)
{ {
e.Use(); e.Use();
} }
@ -161,7 +158,7 @@ namespace Fungus
// Cut keyboard shortcut // Cut keyboard shortcut
if (e.type == EventType.ValidateCommand && e.commandName == "Cut") if (e.type == EventType.ValidateCommand && e.commandName == "Cut")
{ {
if (flowchart.selectedCommands.Count > 0) if (flowchart.SelectedCommands.Count > 0)
{ {
e.Use(); e.Use();
} }
@ -192,7 +189,7 @@ namespace Fungus
// Duplicate keyboard shortcut // Duplicate keyboard shortcut
if (e.type == EventType.ValidateCommand && e.commandName == "Duplicate") if (e.type == EventType.ValidateCommand && e.commandName == "Duplicate")
{ {
if (flowchart.selectedCommands.Count > 0) if (flowchart.SelectedCommands.Count > 0)
{ {
e.Use(); e.Use();
} }
@ -208,7 +205,7 @@ namespace Fungus
// Delete keyboard shortcut // Delete keyboard shortcut
if (e.type == EventType.ValidateCommand && e.commandName == "Delete") if (e.type == EventType.ValidateCommand && e.commandName == "Delete")
{ {
if (flowchart.selectedCommands.Count > 0) if (flowchart.SelectedCommands.Count > 0)
{ {
e.Use(); e.Use();
} }
@ -232,7 +229,6 @@ namespace Fungus
e.Use(); e.Use();
} }
} }
} }
// Remove any null entries in the command list. // Remove any null entries in the command list.
@ -311,9 +307,9 @@ namespace Fungus
Block block = target as Block; Block block = target as Block;
System.Type currentType = null; System.Type currentType = null;
if (block.eventHandler != null) if (block._EventHandler != null)
{ {
currentType = block.eventHandler.GetType(); currentType = block._EventHandler.GetType();
} }
string currentHandlerName = "<None>"; string currentHandlerName = "<None>";
@ -372,9 +368,9 @@ namespace Fungus
} }
EditorGUILayout.EndHorizontal(); EditorGUILayout.EndHorizontal();
if (block.eventHandler != null) if (block._EventHandler != null)
{ {
EventHandlerEditor eventHandlerEditor = Editor.CreateEditor(block.eventHandler) as EventHandlerEditor; EventHandlerEditor eventHandlerEditor = Editor.CreateEditor(block._EventHandler) as EventHandlerEditor;
if (eventHandlerEditor != null) if (eventHandlerEditor != null)
{ {
eventHandlerEditor.DrawInspectorGUI(); eventHandlerEditor.DrawInspectorGUI();
@ -395,16 +391,16 @@ namespace Fungus
Undo.RecordObject(block, "Set Event Handler"); Undo.RecordObject(block, "Set Event Handler");
if (block.eventHandler != null) if (block._EventHandler != null)
{ {
Undo.DestroyObjectImmediate(block.eventHandler); Undo.DestroyObjectImmediate(block._EventHandler);
} }
if (selectedType != null) if (selectedType != null)
{ {
EventHandler newHandler = Undo.AddComponent(block.gameObject, selectedType) as EventHandler; EventHandler newHandler = Undo.AddComponent(block.gameObject, selectedType) as EventHandler;
newHandler.parentBlock = block; newHandler.ParentBlock = block;
block.eventHandler = newHandler; block._EventHandler = newHandler;
} }
// Because this is an async call, we need to force prefab instances to record changes // Because this is an async call, we need to force prefab instances to record changes
@ -428,7 +424,7 @@ namespace Fungus
Block[] blocks = flowchart.GetComponents<Block>(); Block[] blocks = flowchart.GetComponents<Block>();
for (int i = 0; i < blocks.Length; ++i) for (int i = 0; i < blocks.Length; ++i)
{ {
blockNames.Add(new GUIContent(blocks[i].blockName)); blockNames.Add(new GUIContent(blocks[i].BlockName));
if (block == blocks[i]) if (block == blocks[i])
{ {
@ -603,7 +599,7 @@ namespace Fungus
protected static string GetPropertyInfo(System.Type type) protected static string GetPropertyInfo(System.Type type)
{ {
string markdown = ""; string markdown = "";
foreach(FieldInfo field in type.GetFields() ) foreach(FieldInfo field in type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))
{ {
TooltipAttribute attribute = (TooltipAttribute)Attribute.GetCustomAttribute(field, typeof(TooltipAttribute)); TooltipAttribute attribute = (TooltipAttribute)Attribute.GetCustomAttribute(field, typeof(TooltipAttribute));
if (attribute == null ) if (attribute == null )
@ -641,16 +637,16 @@ namespace Fungus
// Use index of last selected command in list, or end of list if nothing selected. // Use index of last selected command in list, or end of list if nothing selected.
int index = -1; int index = -1;
foreach (Command command in flowchart.selectedCommands) foreach (Command command in flowchart.SelectedCommands)
{ {
if (command.commandIndex + 1 > index) if (command.CommandIndex + 1 > index)
{ {
index = command.commandIndex + 1; index = command.CommandIndex + 1;
} }
} }
if (index == -1) if (index == -1)
{ {
index = block.commandList.Count; index = block.CommandList.Count;
} }
GenericMenu commandMenu = new GenericMenu(); GenericMenu commandMenu = new GenericMenu();
@ -738,20 +734,20 @@ namespace Fungus
Command newCommand = Undo.AddComponent(block.gameObject, commandOperation.commandType) as Command; Command newCommand = Undo.AddComponent(block.gameObject, commandOperation.commandType) as Command;
block.GetFlowchart().AddSelectedCommand(newCommand); block.GetFlowchart().AddSelectedCommand(newCommand);
newCommand.parentBlock = block; newCommand.ParentBlock = block;
newCommand.itemId = flowchart.NextItemId(); newCommand.ItemId = flowchart.NextItemId();
// Let command know it has just been added to the block // Let command know it has just been added to the block
newCommand.OnCommandAdded(block); newCommand.OnCommandAdded(block);
Undo.RecordObject(block, "Set command type"); Undo.RecordObject(block, "Set command type");
if (commandOperation.index < block.commandList.Count - 1) if (commandOperation.index < block.CommandList.Count - 1)
{ {
block.commandList.Insert(commandOperation.index, newCommand); block.CommandList.Insert(commandOperation.index, newCommand);
} }
else else
{ {
block.commandList.Add(newCommand); block.CommandList.Add(newCommand);
} }
// Because this is an async call, we need to force prefab instances to record changes // Because this is an async call, we need to force prefab instances to record changes
@ -774,12 +770,12 @@ namespace Fungus
bool showPaste = false; bool showPaste = false;
bool showPlay = false; bool showPlay = false;
if (flowchart.selectedCommands.Count > 0) if (flowchart.SelectedCommands.Count > 0)
{ {
showCut = true; showCut = true;
showCopy = true; showCopy = true;
showDelete = true; showDelete = true;
if (flowchart.selectedCommands.Count == 1 && Application.isPlaying) if (flowchart.SelectedCommands.Count == 1 && Application.isPlaying)
{ {
showPlay = true; showPlay = true;
} }
@ -852,14 +848,14 @@ namespace Fungus
Flowchart flowchart = block.GetFlowchart(); Flowchart flowchart = block.GetFlowchart();
if (flowchart == null || if (flowchart == null ||
flowchart.selectedBlock == null) flowchart.SelectedBlock == null)
{ {
return; return;
} }
flowchart.ClearSelectedCommands(); flowchart.ClearSelectedCommands();
Undo.RecordObject(flowchart, "Select All"); Undo.RecordObject(flowchart, "Select All");
foreach (Command command in flowchart.selectedBlock.commandList) foreach (Command command in flowchart.SelectedBlock.CommandList)
{ {
flowchart.AddSelectedCommand(command); flowchart.AddSelectedCommand(command);
} }
@ -873,7 +869,7 @@ namespace Fungus
Flowchart flowchart = block.GetFlowchart(); Flowchart flowchart = block.GetFlowchart();
if (flowchart == null || if (flowchart == null ||
flowchart.selectedBlock == null) flowchart.SelectedBlock == null)
{ {
return; return;
} }
@ -896,7 +892,7 @@ namespace Fungus
Flowchart flowchart = block.GetFlowchart(); Flowchart flowchart = block.GetFlowchart();
if (flowchart == null || if (flowchart == null ||
flowchart.selectedBlock == null) flowchart.SelectedBlock == null)
{ {
return; return;
} }
@ -905,9 +901,9 @@ namespace Fungus
commandCopyBuffer.Clear(); commandCopyBuffer.Clear();
// Scan through all commands in execution order to see if each needs to be copied // Scan through all commands in execution order to see if each needs to be copied
foreach (Command command in flowchart.selectedBlock.commandList) foreach (Command command in flowchart.SelectedBlock.CommandList)
{ {
if (flowchart.selectedCommands.Contains(command)) if (flowchart.SelectedCommands.Contains(command))
{ {
System.Type type = command.GetType(); System.Type type = command.GetType();
Command newCommand = Undo.AddComponent(commandCopyBuffer.gameObject, type) as Command; Command newCommand = Undo.AddComponent(commandCopyBuffer.gameObject, type) as Command;
@ -926,7 +922,7 @@ namespace Fungus
Flowchart flowchart = block.GetFlowchart(); Flowchart flowchart = block.GetFlowchart();
if (flowchart == null || if (flowchart == null ||
flowchart.selectedBlock == null) flowchart.SelectedBlock == null)
{ {
return; return;
} }
@ -934,14 +930,14 @@ namespace Fungus
CommandCopyBuffer commandCopyBuffer = CommandCopyBuffer.GetInstance(); CommandCopyBuffer commandCopyBuffer = CommandCopyBuffer.GetInstance();
// Find where to paste commands in block (either at end or after last selected command) // Find where to paste commands in block (either at end or after last selected command)
int pasteIndex = flowchart.selectedBlock.commandList.Count; int pasteIndex = flowchart.SelectedBlock.CommandList.Count;
if (flowchart.selectedCommands.Count > 0) if (flowchart.SelectedCommands.Count > 0)
{ {
for (int i = 0; i < flowchart.selectedBlock.commandList.Count; ++i) for (int i = 0; i < flowchart.SelectedBlock.CommandList.Count; ++i)
{ {
Command command = flowchart.selectedBlock.commandList[i]; Command command = flowchart.SelectedBlock.CommandList[i];
foreach (Command selectedCommand in flowchart.selectedCommands) foreach (Command selectedCommand in flowchart.SelectedCommands)
{ {
if (command == selectedCommand) if (command == selectedCommand)
{ {
@ -963,8 +959,8 @@ namespace Fungus
Command pastedCommand = commands.Last<Command>(); Command pastedCommand = commands.Last<Command>();
if (pastedCommand != null) if (pastedCommand != null)
{ {
pastedCommand.itemId = flowchart.NextItemId(); pastedCommand.ItemId = flowchart.NextItemId();
flowchart.selectedBlock.commandList.Insert(pasteIndex++, pastedCommand); flowchart.SelectedBlock.CommandList.Insert(pasteIndex++, pastedCommand);
} }
} }
@ -985,15 +981,15 @@ namespace Fungus
Flowchart flowchart = block.GetFlowchart(); Flowchart flowchart = block.GetFlowchart();
if (flowchart == null || if (flowchart == null ||
flowchart.selectedBlock == null) flowchart.SelectedBlock == null)
{ {
return; return;
} }
int lastSelectedIndex = 0; int lastSelectedIndex = 0;
for (int i = flowchart.selectedBlock.commandList.Count - 1; i >= 0; --i) for (int i = flowchart.SelectedBlock.CommandList.Count - 1; i >= 0; --i)
{ {
Command command = flowchart.selectedBlock.commandList[i]; Command command = flowchart.SelectedBlock.CommandList[i];
foreach (Command selectedCommand in flowchart.selectedCommands) foreach (Command selectedCommand in flowchart.SelectedCommands)
{ {
if (command == selectedCommand) if (command == selectedCommand)
{ {
@ -1002,8 +998,8 @@ namespace Fungus
// Order of destruction is important here for undo to work // Order of destruction is important here for undo to work
Undo.DestroyObjectImmediate(command); Undo.DestroyObjectImmediate(command);
Undo.RecordObject(flowchart.selectedBlock, "Delete"); Undo.RecordObject(flowchart.SelectedBlock, "Delete");
flowchart.selectedBlock.commandList.RemoveAt(i); flowchart.SelectedBlock.CommandList.RemoveAt(i);
lastSelectedIndex = i; lastSelectedIndex = i;
@ -1015,9 +1011,9 @@ namespace Fungus
Undo.RecordObject(flowchart, "Delete"); Undo.RecordObject(flowchart, "Delete");
flowchart.ClearSelectedCommands(); flowchart.ClearSelectedCommands();
if (lastSelectedIndex < flowchart.selectedBlock.commandList.Count) if (lastSelectedIndex < flowchart.SelectedBlock.CommandList.Count)
{ {
Command nextCommand = flowchart.selectedBlock.commandList[lastSelectedIndex]; Command nextCommand = flowchart.SelectedBlock.CommandList[lastSelectedIndex];
block.GetFlowchart().AddSelectedCommand(nextCommand); block.GetFlowchart().AddSelectedCommand(nextCommand);
} }
@ -1028,19 +1024,19 @@ namespace Fungus
{ {
Block targetBlock = target as Block; Block targetBlock = target as Block;
Flowchart flowchart = targetBlock.GetFlowchart(); Flowchart flowchart = targetBlock.GetFlowchart();
Command command = flowchart.selectedCommands[0]; Command command = flowchart.SelectedCommands[0];
if (targetBlock.IsExecuting()) if (targetBlock.IsExecuting())
{ {
// The Block is already executing. // The Block is already executing.
// Tell the Block to stop, wait a little while so the executing command has a // Tell the Block to stop, wait a little while so the executing command has a
// chance to stop, and then start execution again from the new command. // chance to stop, and then start execution again from the new command.
targetBlock.Stop(); targetBlock.Stop();
flowchart.StartCoroutine(RunBlock(flowchart, targetBlock, command.commandIndex, 0.2f)); flowchart.StartCoroutine(RunBlock(flowchart, targetBlock, command.CommandIndex, 0.2f));
} }
else else
{ {
// Block isn't executing yet so can start it now. // Block isn't executing yet so can start it now.
flowchart.ExecuteBlock(targetBlock, command.commandIndex); flowchart.ExecuteBlock(targetBlock, command.CommandIndex);
} }
} }
@ -1048,11 +1044,11 @@ namespace Fungus
{ {
Block targetBlock = target as Block; Block targetBlock = target as Block;
Flowchart flowchart = targetBlock.GetFlowchart(); Flowchart flowchart = targetBlock.GetFlowchart();
Command command = flowchart.selectedCommands[0]; Command command = flowchart.SelectedCommands[0];
// Stop all active blocks then run the selected block. // Stop all active blocks then run the selected block.
flowchart.StopAllBlocks(); flowchart.StopAllBlocks();
flowchart.StartCoroutine(RunBlock(flowchart, targetBlock, command.commandIndex, 0.2f)); flowchart.StartCoroutine(RunBlock(flowchart, targetBlock, command.CommandIndex, 0.2f));
} }
protected IEnumerator RunBlock(Flowchart flowchart, Block targetBlock, int commandIndex, float delay) protected IEnumerator RunBlock(Flowchart flowchart, Block targetBlock, int commandIndex, float delay)
@ -1066,15 +1062,15 @@ namespace Fungus
Block block = target as Block; Block block = target as Block;
Flowchart flowchart = block.GetFlowchart(); Flowchart flowchart = block.GetFlowchart();
int firstSelectedIndex = flowchart.selectedBlock.commandList.Count; int firstSelectedIndex = flowchart.SelectedBlock.CommandList.Count;
bool firstSelectedCommandFound = false; bool firstSelectedCommandFound = false;
if (flowchart.selectedCommands.Count > 0) if (flowchart.SelectedCommands.Count > 0)
{ {
for (int i = 0; i < flowchart.selectedBlock.commandList.Count; i++) for (int i = 0; i < flowchart.SelectedBlock.CommandList.Count; i++)
{ {
Command commandInBlock = flowchart.selectedBlock.commandList[i]; Command commandInBlock = flowchart.SelectedBlock.CommandList[i];
foreach (Command selectedCommand in flowchart.selectedCommands) foreach (Command selectedCommand in flowchart.SelectedCommands)
{ {
if (commandInBlock == selectedCommand) if (commandInBlock == selectedCommand)
{ {
@ -1095,7 +1091,7 @@ namespace Fungus
if (firstSelectedIndex > 0) if (firstSelectedIndex > 0)
{ {
flowchart.ClearSelectedCommands(); flowchart.ClearSelectedCommands();
flowchart.AddSelectedCommand(flowchart.selectedBlock.commandList[firstSelectedIndex-1]); flowchart.AddSelectedCommand(flowchart.SelectedBlock.CommandList[firstSelectedIndex-1]);
} }
Repaint(); Repaint();
@ -1107,13 +1103,13 @@ namespace Fungus
Flowchart flowchart = block.GetFlowchart(); Flowchart flowchart = block.GetFlowchart();
int lastSelectedIndex = -1; int lastSelectedIndex = -1;
if (flowchart.selectedCommands.Count > 0) if (flowchart.SelectedCommands.Count > 0)
{ {
for (int i = 0; i < flowchart.selectedBlock.commandList.Count; i++) for (int i = 0; i < flowchart.SelectedBlock.CommandList.Count; i++)
{ {
Command commandInBlock = flowchart.selectedBlock.commandList[i]; Command commandInBlock = flowchart.SelectedBlock.CommandList[i];
foreach (Command selectedCommand in flowchart.selectedCommands) foreach (Command selectedCommand in flowchart.SelectedCommands)
{ {
if (commandInBlock == selectedCommand) if (commandInBlock == selectedCommand)
{ {
@ -1122,14 +1118,13 @@ namespace Fungus
} }
} }
} }
if (lastSelectedIndex < flowchart.selectedBlock.commandList.Count-1) if (lastSelectedIndex < flowchart.SelectedBlock.CommandList.Count-1)
{ {
flowchart.ClearSelectedCommands(); flowchart.ClearSelectedCommands();
flowchart.AddSelectedCommand(flowchart.selectedBlock.commandList[lastSelectedIndex+1]); flowchart.AddSelectedCommand(flowchart.SelectedBlock.CommandList[lastSelectedIndex+1]);
} }
Repaint(); Repaint();
} }
} }
} }

39
Assets/Fungus/Flowchart/Editor/BlockInspector.cs

@ -1,30 +1,26 @@
/** // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
using UnityEngine; using UnityEngine;
using UnityEngine.Serialization; using UnityEngine.Serialization;
using UnityEditor; using UnityEditor;
using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
namespace Fungus namespace Fungus
{ {
/** /// <summary>
* Temp hidden object which lets us use the entire inspector window to inspect /// Temp hidden object which lets us use the entire inspector window to inspect the block command list.
* the block command list. /// </summary>
*/
public class BlockInspector : ScriptableObject public class BlockInspector : ScriptableObject
{ {
[FormerlySerializedAs("sequence")] [FormerlySerializedAs("sequence")]
public Block block; public Block block;
} }
/** /// <summary>
* Custom editor for the temp hidden object. /// Custom editor for the temp hidden object.
*/ /// </summary>
[CustomEditor (typeof(BlockInspector), true)] [CustomEditor (typeof(BlockInspector), true)]
public class BlockInspectorEditor : Editor public class BlockInspectorEditor : Editor
{ {
@ -101,19 +97,19 @@ namespace Fungus
Rect blockRect = new Rect(5, topPanelHeight, width - 5, height + 10); Rect blockRect = new Rect(5, topPanelHeight, width - 5, height + 10);
GUILayout.BeginArea(blockRect); GUILayout.BeginArea(blockRect);
blockScrollPos = GUILayout.BeginScrollView(blockScrollPos, GUILayout.Height(flowchart.blockViewHeight)); blockScrollPos = GUILayout.BeginScrollView(blockScrollPos, GUILayout.Height(flowchart.BlockViewHeight));
activeBlockEditor.DrawBlockGUI(flowchart); activeBlockEditor.DrawBlockGUI(flowchart);
GUILayout.EndScrollView(); GUILayout.EndScrollView();
Command inspectCommand = null; Command inspectCommand = null;
if (flowchart.selectedCommands.Count == 1) if (flowchart.SelectedCommands.Count == 1)
{ {
inspectCommand = flowchart.selectedCommands[0]; inspectCommand = flowchart.SelectedCommands[0];
} }
if (Application.isPlaying && if (Application.isPlaying &&
inspectCommand != null && inspectCommand != null &&
inspectCommand.parentBlock != block) inspectCommand.ParentBlock != block)
{ {
GUILayout.EndArea(); GUILayout.EndArea();
Repaint(); Repaint();
@ -189,7 +185,7 @@ namespace Fungus
// Draw the resize bar after everything else has finished drawing // Draw the resize bar after everything else has finished drawing
// This is mainly to avoid incorrect indenting. // This is mainly to avoid incorrect indenting.
Rect resizeRect = new Rect(0, topPanelHeight + flowchart.blockViewHeight + 1, Screen.width, 4f); Rect resizeRect = new Rect(0, topPanelHeight + flowchart.BlockViewHeight + 1, Screen.width, 4f);
GUI.color = new Color(0.64f, 0.64f, 0.64f); GUI.color = new Color(0.64f, 0.64f, 0.64f);
GUI.DrawTexture(resizeRect, EditorGUIUtility.whiteTexture); GUI.DrawTexture(resizeRect, EditorGUIUtility.whiteTexture);
resizeRect.height = 1; resizeRect.height = 1;
@ -204,7 +200,7 @@ namespace Fungus
private void ResizeScrollView(Flowchart flowchart) private void ResizeScrollView(Flowchart flowchart)
{ {
Rect cursorChangeRect = new Rect(0, flowchart.blockViewHeight + 1, Screen.width, 4f); Rect cursorChangeRect = new Rect(0, flowchart.BlockViewHeight + 1, Screen.width, 4f);
EditorGUIUtility.AddCursorRect(cursorChangeRect, MouseCursor.ResizeVertical); EditorGUIUtility.AddCursorRect(cursorChangeRect, MouseCursor.ResizeVertical);
@ -216,7 +212,7 @@ namespace Fungus
if (resize) if (resize)
{ {
Undo.RecordObject(flowchart, "Resize view"); Undo.RecordObject(flowchart, "Resize view");
flowchart.blockViewHeight = Event.current.mousePosition.y; flowchart.BlockViewHeight = Event.current.mousePosition.y;
} }
ClampBlockViewHeight(flowchart); ClampBlockViewHeight(flowchart);
@ -251,10 +247,10 @@ namespace Fungus
if (clamp) if (clamp)
{ {
// Make sure block view is always clamped to visible area // Make sure block view is always clamped to visible area
float height = flowchart.blockViewHeight; float height = flowchart.BlockViewHeight;
height = Mathf.Max(200, height); height = Mathf.Max(200, height);
height = Mathf.Min(Screen.height - 200,height); height = Mathf.Min(Screen.height - 200,height);
flowchart.blockViewHeight = height; flowchart.BlockViewHeight = height;
} }
if (Event.current.type == EventType.Repaint) if (Event.current.type == EventType.Repaint)
@ -263,5 +259,4 @@ namespace Fungus
} }
} }
} }
} }

9
Assets/Fungus/Flowchart/Editor/CallEditor.cs

@ -1,12 +1,8 @@
/** // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
using UnityEditor; using UnityEditor;
using UnityEngine; using UnityEngine;
using System.Collections;
using System.Collections.Generic;
namespace Fungus namespace Fungus
{ {
@ -62,5 +58,4 @@ namespace Fungus
serializedObject.ApplyModifiedProperties(); serializedObject.ApplyModifiedProperties();
} }
} }
} }

30
Assets/Fungus/Flowchart/Editor/CommandEditor.cs

@ -1,12 +1,8 @@
/** // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
using UnityEditor; using UnityEditor;
using UnityEditorInternal;
using UnityEngine; using UnityEngine;
using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using Rotorz.ReorderableList; using Rotorz.ReorderableList;
@ -57,7 +53,7 @@ namespace Fungus
if (t.enabled) if (t.enabled)
{ {
if (flowchart.colorCommands) if (flowchart.ColorCommands)
{ {
GUI.backgroundColor = t.GetButtonColor(); GUI.backgroundColor = t.GetButtonColor();
} }
@ -77,7 +73,7 @@ namespace Fungus
GUILayout.FlexibleSpace(); GUILayout.FlexibleSpace();
GUILayout.Label(new GUIContent("(" + t.itemId + ")")); GUILayout.Label(new GUIContent("(" + t.ItemId + ")"));
GUILayout.Space(10); GUILayout.Space(10);
@ -100,11 +96,11 @@ namespace Fungus
EditorGUILayout.Separator(); EditorGUILayout.Separator();
if (t.errorMessage.Length > 0) if (t.ErrorMessage.Length > 0)
{ {
GUIStyle style = new GUIStyle(GUI.skin.label); GUIStyle style = new GUIStyle(GUI.skin.label);
style.normal.textColor = new Color(1,0,0); style.normal.textColor = new Color(1,0,0);
EditorGUILayout.LabelField(new GUIContent("Error: " + t.errorMessage), style); EditorGUILayout.LabelField(new GUIContent("Error: " + t.ErrorMessage), style);
} }
GUILayout.EndVertical(); GUILayout.EndVertical();
@ -202,14 +198,12 @@ namespace Fungus
} }
/** // When modifying custom editor code you can occasionally end up with orphaned editor instances.
* When modifying custom editor code you can occasionally end up with orphaned editor instances. // When this happens, you'll get a null exception error every time the scene serializes / deserialized.
* When this happens, you'll get a null exception error every time the scene serializes / deserialized. // Once this situation occurs, the only way to fix it is to restart the Unity editor.
* Once this situation occurs, the only way to fix it is to restart the Unity editor. //
* // As a workaround, this function detects if this command editor is an orphan and deletes it.
* As a workaround, this function detects if this command editor is an orphan and deletes it. // To use it, just call this function at the top of the OnEnable() method in your custom editor.
* To use it, just call this function at the top of the OnEnable() method in your custom editor.
*/
protected virtual bool NullTargetCheck() protected virtual bool NullTargetCheck()
{ {
try try

58
Assets/Fungus/Flowchart/Editor/CommandListAdaptor.cs

@ -1,7 +1,5 @@
/** // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
// Copyright (c) 2012-2013 Rotorz Limited. All rights reserved. // Copyright (c) 2012-2013 Rotorz Limited. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be // Use of this source code is governed by a BSD-style license that can be
@ -10,8 +8,6 @@
using UnityEngine; using UnityEngine;
using UnityEditor; using UnityEditor;
using System; using System;
using System.Collections.Generic;
using System.Linq;
using Rotorz.ReorderableList; using Rotorz.ReorderableList;
namespace Fungus namespace Fungus
@ -88,14 +84,14 @@ namespace Fungus
return null; return null;
} }
Block block = flowchart.selectedBlock; Block block = flowchart.SelectedBlock;
if (block == null) if (block == null)
{ {
return null; return null;
} }
Command newCommand = Undo.AddComponent<Comment>(block.gameObject) as Command; Command newCommand = Undo.AddComponent<Comment>(block.gameObject) as Command;
newCommand.itemId = flowchart.NextItemId(); newCommand.ItemId = flowchart.NextItemId();
flowchart.ClearSelectedCommands(); flowchart.ClearSelectedCommands();
flowchart.AddSelectedCommand(newCommand); flowchart.AddSelectedCommand(newCommand);
@ -111,7 +107,7 @@ namespace Fungus
System.Type type = command.GetType(); System.Type type = command.GetType();
Command newCommand = Undo.AddComponent(parentBlock.gameObject, type) as Command; Command newCommand = Undo.AddComponent(parentBlock.gameObject, type) as Command;
newCommand.itemId = newCommand.GetFlowchart().NextItemId(); newCommand.ItemId = newCommand.GetFlowchart().NextItemId();
System.Reflection.FieldInfo[] fields = type.GetFields(); System.Reflection.FieldInfo[] fields = type.GetFields();
foreach (System.Reflection.FieldInfo field in fields) foreach (System.Reflection.FieldInfo field in fields)
{ {
@ -205,7 +201,7 @@ namespace Fungus
} }
bool commandIsSelected = false; bool commandIsSelected = false;
foreach (Command selectedCommand in flowchart.selectedCommands) foreach (Command selectedCommand in flowchart.SelectedCommands)
{ {
if (selectedCommand == command) if (selectedCommand == command)
{ {
@ -229,7 +225,7 @@ namespace Fungus
commandLabelStyle.padding.top -= 1; commandLabelStyle.padding.top -= 1;
float indentSize = 20; float indentSize = 20;
for (int i = 0; i < command.indentLevel; ++i) for (int i = 0; i < command.IndentLevel; ++i)
{ {
Rect indentRect = position; Rect indentRect = position;
indentRect.x += i * indentSize - 21; indentRect.x += i * indentSize - 21;
@ -241,12 +237,12 @@ namespace Fungus
} }
float commandNameWidth = Mathf.Max(commandLabelStyle.CalcSize(new GUIContent(commandName)).x, 90f); float commandNameWidth = Mathf.Max(commandLabelStyle.CalcSize(new GUIContent(commandName)).x, 90f);
float indentWidth = command.indentLevel * indentSize; float indentWidth = command.IndentLevel * indentSize;
Rect commandLabelRect = position; Rect commandLabelRect = position;
commandLabelRect.x += indentWidth - 21; commandLabelRect.x += indentWidth - 21;
commandLabelRect.y -= 2; commandLabelRect.y -= 2;
commandLabelRect.width -= (indentSize * command.indentLevel - 22); commandLabelRect.width -= (indentSize * command.IndentLevel - 22);
commandLabelRect.height += 5; commandLabelRect.height += 5;
// There's a weird incompatibility between the Reorderable list control used for the command list and // There's a weird incompatibility between the Reorderable list control used for the command list and
@ -263,14 +259,14 @@ namespace Fungus
Event.current.button == 0 && Event.current.button == 0 &&
clickRect.Contains(Event.current.mousePosition)) clickRect.Contains(Event.current.mousePosition))
{ {
if (flowchart.selectedCommands.Contains(command) && Event.current.button == 0) if (flowchart.SelectedCommands.Contains(command) && Event.current.button == 0)
{ {
// Left click on already selected command // Left click on already selected command
// Command key and shift key is not pressed // Command key and shift key is not pressed
if (!EditorGUI.actionKey && !Event.current.shift) if (!EditorGUI.actionKey && !Event.current.shift)
{ {
BlockEditor.actionList.Add ( delegate { BlockEditor.actionList.Add ( delegate {
flowchart.selectedCommands.Remove(command); flowchart.SelectedCommands.Remove(command);
flowchart.ClearSelectedCommands(); flowchart.ClearSelectedCommands();
}); });
} }
@ -279,7 +275,7 @@ namespace Fungus
if (EditorGUI.actionKey) if (EditorGUI.actionKey)
{ {
BlockEditor.actionList.Add ( delegate { BlockEditor.actionList.Add ( delegate {
flowchart.selectedCommands.Remove(command); flowchart.SelectedCommands.Remove(command);
}); });
Event.current.Use(); Event.current.Use();
} }
@ -304,14 +300,14 @@ namespace Fungus
// Find first and last selected commands // Find first and last selected commands
int firstSelectedIndex = -1; int firstSelectedIndex = -1;
int lastSelectedIndex = -1; int lastSelectedIndex = -1;
if (flowchart.selectedCommands.Count > 0) if (flowchart.SelectedCommands.Count > 0)
{ {
if ( flowchart.selectedBlock != null) if ( flowchart.SelectedBlock != null)
{ {
for (int i = 0; i < flowchart.selectedBlock.commandList.Count; i++) for (int i = 0; i < flowchart.SelectedBlock.CommandList.Count; i++)
{ {
Command commandInBlock = flowchart.selectedBlock.commandList[i]; Command commandInBlock = flowchart.SelectedBlock.CommandList[i];
foreach (Command selectedCommand in flowchart.selectedCommands) foreach (Command selectedCommand in flowchart.SelectedCommands)
{ {
if (commandInBlock == selectedCommand) if (commandInBlock == selectedCommand)
{ {
@ -320,10 +316,10 @@ namespace Fungus
} }
} }
} }
for (int i = flowchart.selectedBlock.commandList.Count - 1; i >=0; i--) for (int i = flowchart.SelectedBlock.CommandList.Count - 1; i >=0; i--)
{ {
Command commandInBlock = flowchart.selectedBlock.commandList[i]; Command commandInBlock = flowchart.SelectedBlock.CommandList[i];
foreach (Command selectedCommand in flowchart.selectedCommands) foreach (Command selectedCommand in flowchart.SelectedCommands)
{ {
if (commandInBlock == selectedCommand) if (commandInBlock == selectedCommand)
{ {
@ -337,7 +333,7 @@ namespace Fungus
if (shift) if (shift)
{ {
int currentIndex = command.commandIndex; int currentIndex = command.CommandIndex;
if (firstSelectedIndex == -1 || if (firstSelectedIndex == -1 ||
lastSelectedIndex == -1) lastSelectedIndex == -1)
{ {
@ -359,7 +355,7 @@ namespace Fungus
for (int i = Math.Min(firstSelectedIndex, lastSelectedIndex); i < Math.Max(firstSelectedIndex, lastSelectedIndex); ++i) for (int i = Math.Min(firstSelectedIndex, lastSelectedIndex); i < Math.Max(firstSelectedIndex, lastSelectedIndex); ++i)
{ {
Command selectedCommand = flowchart.selectedBlock.commandList[i]; Command selectedCommand = flowchart.SelectedBlock.CommandList[i];
BlockEditor.actionList.Add ( delegate { BlockEditor.actionList.Add ( delegate {
flowchart.AddSelectedCommand(selectedCommand); flowchart.AddSelectedCommand(selectedCommand);
}); });
@ -372,7 +368,7 @@ namespace Fungus
} }
Color commandLabelColor = Color.white; Color commandLabelColor = Color.white;
if (flowchart.colorCommands) if (flowchart.ColorCommands)
{ {
commandLabelColor = command.GetButtonColor(); commandLabelColor = command.GetButtonColor();
} }
@ -399,9 +395,9 @@ namespace Fungus
else else
{ {
string commandNameLabel; string commandNameLabel;
if (flowchart.showLineNumbers) if (flowchart.ShowLineNumbers)
{ {
commandNameLabel = command.commandIndex.ToString() + ": " + commandName; commandNameLabel = command.CommandIndex.ToString() + ": " + commandName;
} }
else else
{ {
@ -411,7 +407,7 @@ namespace Fungus
GUI.Label(commandLabelRect, commandNameLabel, commandLabelStyle); GUI.Label(commandLabelRect, commandNameLabel, commandLabelStyle);
} }
if (command.executingIconTimer > Time.realtimeSinceStartup) if (command.ExecutingIconTimer > Time.realtimeSinceStartup)
{ {
Rect iconRect = new Rect(commandLabelRect); Rect iconRect = new Rect(commandLabelRect);
iconRect.x += iconRect.width - commandLabelRect.width - 20; iconRect.x += iconRect.width - commandLabelRect.width - 20;
@ -420,7 +416,7 @@ namespace Fungus
Color storeColor = GUI.color; Color storeColor = GUI.color;
float alpha = (command.executingIconTimer - Time.realtimeSinceStartup) / Block.executingIconFadeTime; float alpha = (command.ExecutingIconTimer - Time.realtimeSinceStartup) / Block.executingIconFadeTime;
alpha = Mathf.Clamp01(alpha); alpha = Mathf.Clamp01(alpha);
GUI.color = new Color(1f, 1f, 1f, alpha); GUI.color = new Color(1f, 1f, 1f, alpha);

18
Assets/Fungus/Flowchart/Editor/CustomGUI.cs

@ -1,20 +1,13 @@
/** // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
using UnityEngine; using UnityEngine;
using UnityEngine.Internal;
using UnityEditor;
using System;
using System.Reflection;
namespace Fungus namespace Fungus
{ {
/// <summary>
/** /// Utility functions for drawing custom UI in the editor.
* Utility functions for drawing custom UI in the editor /// </summary>
*/
public static class CustomGUI public static class CustomGUI
{ {
public static Texture2D CreateBlackTexture() public static Texture2D CreateBlackTexture()
@ -46,5 +39,4 @@ namespace Fungus
GUILayout.Box(blackTex,separatorStyle); GUILayout.Box(blackTex,separatorStyle);
} }
} }
} }

9
Assets/Fungus/Flowchart/Editor/EditorExtensions.cs

@ -1,16 +1,12 @@
/** // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
using UnityEngine; using UnityEngine;
using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
namespace Fungus namespace Fungus
{ {
public static class EditorExtensions public static class EditorExtensions
{ {
/// <summary> /// <summary>
@ -68,5 +64,4 @@ namespace Fungus
return FindDerivedTypesFromAssembly(System.Reflection.Assembly.GetAssembly(baseType), baseType, classOnly); return FindDerivedTypesFromAssembly(System.Reflection.Assembly.GetAssembly(baseType), baseType, classOnly);
} }
} }
} }

8
Assets/Fungus/Flowchart/Editor/EditorZoomArea.cs

@ -1,7 +1,5 @@
/** // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
// Original code by Martin Ecker (http://martinecker.com) // Original code by Martin Ecker (http://martinecker.com)
@ -9,7 +7,6 @@ using UnityEngine;
namespace Fungus namespace Fungus
{ {
// Helper Rect extension methods // Helper Rect extension methods
public static class RectExtensions public static class RectExtensions
{ {
@ -87,5 +84,4 @@ namespace Fungus
GUI.BeginGroup(new Rect(0.0f, kEditorWindowTabHeight, Screen.width, Screen.height)); GUI.BeginGroup(new Rect(0.0f, kEditorWindowTabHeight, Screen.width, Screen.height));
} }
} }
} }

17
Assets/Fungus/Flowchart/Editor/EventHandlerEditor.cs

@ -1,23 +1,17 @@
/** // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
using UnityEditor; using UnityEditor;
using UnityEditorInternal;
using UnityEngine; using UnityEngine;
using System.Collections;
using System.Collections.Generic;
namespace Fungus namespace Fungus
{ {
[CustomEditor (typeof(EventHandler), true)] [CustomEditor (typeof(EventHandler), true)]
public class EventHandlerEditor : Editor public class EventHandlerEditor : Editor
{ {
/** /// <summary>
* Returns the class attribute info for an event handler class. /// Returns the class attribute info for an event handler class.
*/ /// </summary>
public static EventHandlerInfoAttribute GetEventHandlerInfo(System.Type eventHandlerType) public static EventHandlerInfoAttribute GetEventHandlerInfo(System.Type eventHandlerType)
{ {
object[] attributes = eventHandlerType.GetCustomAttributes(typeof(EventHandlerInfoAttribute), false); object[] attributes = eventHandlerType.GetCustomAttributes(typeof(EventHandlerInfoAttribute), false);
@ -64,5 +58,4 @@ namespace Fungus
serializedObject.ApplyModifiedProperties(); serializedObject.ApplyModifiedProperties();
} }
} }
} }

6
Assets/Fungus/Flowchart/Editor/Extensions/SerializedPropertyExtensions.cs

@ -1,7 +1,5 @@
/** // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
using UnityEditor; using UnityEditor;
using UnityEngine; using UnityEngine;

49
Assets/Fungus/Flowchart/Editor/FlowchartEditor.cs

@ -1,16 +1,12 @@
/** // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
using UnityEditor; using UnityEditor;
using UnityEngine; using UnityEngine;
using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using Rotorz.ReorderableList; using Rotorz.ReorderableList;
using System.Linq; using System.Linq;
using System.Reflection; using System.Reflection;
using System.IO;
namespace Fungus namespace Fungus
{ {
@ -91,8 +87,8 @@ namespace Fungus
if (GUILayout.Button(new GUIContent("Center View", "Centers the window view at the center of all blocks in the Flowchart"))) if (GUILayout.Button(new GUIContent("Center View", "Centers the window view at the center of all blocks in the Flowchart")))
{ {
// Reset the zoom so we don't have adjust the center position depending on zoom // Reset the zoom so we don't have adjust the center position depending on zoom
flowchart.scrollPos = flowchart.centerPosition; flowchart.ScrollPos = flowchart.CenterPosition;
flowchart.zoom = FlowchartWindow.maxZoomValue; flowchart.Zoom = FlowchartWindow.maxZoomValue;
} }
GUILayout.FlexibleSpace(); GUILayout.FlexibleSpace();
GUILayout.EndHorizontal(); GUILayout.EndHorizontal();
@ -106,16 +102,16 @@ namespace Fungus
Flowchart t = target as Flowchart; Flowchart t = target as Flowchart;
if (t.variables.Count == 0) if (t.Variables.Count == 0)
{ {
t.variablesExpanded = true; t.VariablesExpanded = true;
} }
if (!t.variablesExpanded) if (!t.VariablesExpanded)
{ {
if (GUILayout.Button ("Variables (" + t.variables.Count + ")", GUILayout.Height(24))) if (GUILayout.Button ("Variables (" + t.Variables.Count + ")", GUILayout.Height(24)))
{ {
t.variablesExpanded = true; t.VariablesExpanded = true;
} }
// Draw disclosure triangle // Draw disclosure triangle
@ -128,15 +124,15 @@ namespace Fungus
{ {
Rect listRect = new Rect(); Rect listRect = new Rect();
if (t.variables.Count > 0) if (t.Variables.Count > 0)
{ {
// Remove any null variables from the list // Remove any null variables from the list
// Can sometimes happen when upgrading to a new version of Fungus (if .meta GUID changes for a variable class) // Can sometimes happen when upgrading to a new version of Fungus (if .meta GUID changes for a variable class)
for (int i = t.variables.Count - 1; i >= 0; i--) for (int i = t.Variables.Count - 1; i >= 0; i--)
{ {
if (t.variables[i] == null) if (t.Variables[i] == null)
{ {
t.variables.RemoveAt(i); t.Variables.RemoveAt(i);
} }
} }
@ -170,7 +166,7 @@ namespace Fungus
if (GUI.Button (buttonRect, "Variables")) if (GUI.Button (buttonRect, "Variables"))
{ {
t.variablesExpanded = false; t.VariablesExpanded = false;
} }
// Draw disclosure triangle // Draw disclosure triangle
@ -249,8 +245,8 @@ namespace Fungus
Undo.RecordObject(flowchart, "Add Variable"); Undo.RecordObject(flowchart, "Add Variable");
Variable newVariable = flowchart.gameObject.AddComponent(variableType) as Variable; Variable newVariable = flowchart.gameObject.AddComponent(variableType) as Variable;
newVariable.key = flowchart.GetUniqueVariableKey(""); newVariable.Key = flowchart.GetUniqueVariableKey("");
flowchart.variables.Add(newVariable); flowchart.Variables.Add(newVariable);
// Because this is an async call, we need to force prefab instances to record changes // Because this is an async call, we need to force prefab instances to record changes
PrefabUtility.RecordPrefabInstancePropertyModifications(flowchart); PrefabUtility.RecordPrefabInstancePropertyModifications(flowchart);
@ -273,12 +269,12 @@ namespace Fungus
} }
/** /// <summary>
* When modifying custom editor code you can occasionally end up with orphaned editor instances. /// When modifying custom editor code you can occasionally end up with orphaned editor instances.
* When this happens, you'll get a null exception error every time the scene serializes / deserialized. /// When this happens, you'll get a null exception error every time the scene serializes / deserialized.
* Once this situation occurs, the only way to fix it is to restart the Unity editor. /// Once this situation occurs, the only way to fix it is to restart the Unity editor.
* As a workaround, this function detects if this editor is an orphan and deletes it. /// As a workaround, this function detects if this editor is an orphan and deletes it.
*/ /// </summary>
protected virtual bool NullTargetCheck() protected virtual bool NullTargetCheck()
{ {
try try
@ -297,5 +293,4 @@ namespace Fungus
return false; return false;
} }
} }
} }

16
Assets/Fungus/Flowchart/Editor/FlowchartMenuItems.cs

@ -1,16 +1,11 @@
/** // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
using UnityEngine; using UnityEngine;
using UnityEditor; using UnityEditor;
using System.IO;
using System.Collections;
namespace Fungus namespace Fungus
{ {
public class FlowchartMenuItems public class FlowchartMenuItems
{ {
[MenuItem("Tools/Fungus/Create/Flowchart", false, 0)] [MenuItem("Tools/Fungus/Create/Flowchart", false, 0)]
@ -23,15 +18,15 @@ namespace Fungus
Flowchart flowchart = go.GetComponent<Flowchart>(); Flowchart flowchart = go.GetComponent<Flowchart>();
if (flowchart != null) if (flowchart != null)
{ {
flowchart.version = Flowchart.CURRENT_VERSION; flowchart.Version = Flowchart.CURRENT_VERSION;
} }
// Only the first created Flowchart in the scene should have a default GameStarted block // Only the first created Flowchart in the scene should have a default GameStarted block
if (GameObject.FindObjectsOfType<Flowchart>().Length > 1) if (GameObject.FindObjectsOfType<Flowchart>().Length > 1)
{ {
Block block = go.GetComponent<Block>(); Block block = go.GetComponent<Block>();
block.eventHandler = null; block._EventHandler = null;
GameObject.DestroyImmediate(block.eventHandler); GameObject.DestroyImmediate(block._EventHandler);
} }
} }
@ -82,5 +77,4 @@ namespace Fungus
return go; return go;
} }
} }
} }

220
Assets/Fungus/Flowchart/Editor/FlowchartWindow.cs

@ -1,14 +1,11 @@
/** // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
using UnityEngine; using UnityEngine;
using UnityEditor; using UnityEditor;
using UnityEditorInternal; using UnityEditorInternal;
using System; using System;
using System.Linq; using System.Linq;
using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
namespace Fungus namespace Fungus
@ -71,13 +68,13 @@ namespace Fungus
} }
if (Selection.activeGameObject == null && if (Selection.activeGameObject == null &&
flowchart.selectedBlock != null) flowchart.SelectedBlock != null)
{ {
if (blockInspector == null) if (blockInspector == null)
{ {
ShowBlockInspector(flowchart); ShowBlockInspector(flowchart);
} }
blockInspector.block = flowchart.selectedBlock; blockInspector.block = flowchart.SelectedBlock;
} }
forceRepaintCount--; forceRepaintCount--;
@ -103,11 +100,11 @@ namespace Fungus
Flowchart fs = Selection.activeGameObject.GetComponent<Flowchart>(); Flowchart fs = Selection.activeGameObject.GetComponent<Flowchart>();
if (fs != null) if (fs != null)
{ {
fungusState.selectedFlowchart = fs; fungusState.SelectedFlowchart = fs;
} }
} }
return fungusState.selectedFlowchart; return fungusState.SelectedFlowchart;
} }
protected virtual void OnGUI() protected virtual void OnGUI()
@ -122,9 +119,9 @@ namespace Fungus
// Delete any scheduled objects // Delete any scheduled objects
foreach (Block deleteBlock in deleteList) foreach (Block deleteBlock in deleteList)
{ {
bool isSelected = (flowchart.selectedBlock == deleteBlock); bool isSelected = (flowchart.SelectedBlock == deleteBlock);
foreach (Command command in deleteBlock.commandList) foreach (Command command in deleteBlock.CommandList)
{ {
Undo.DestroyObjectImmediate(command); Undo.DestroyObjectImmediate(command);
} }
@ -160,22 +157,22 @@ namespace Fungus
if (GUILayout.Button(new GUIContent(addTexture, "Add a new block"))) if (GUILayout.Button(new GUIContent(addTexture, "Add a new block")))
{ {
Vector2 newNodePosition = new Vector2(50 - flowchart.scrollPos.x, Vector2 newNodePosition = new Vector2(50 - flowchart.ScrollPos.x,
50 - flowchart.scrollPos.y); 50 - flowchart.ScrollPos.y);
CreateBlock(flowchart, newNodePosition); CreateBlock(flowchart, newNodePosition);
} }
GUILayout.Space(8); GUILayout.Space(8);
flowchart.zoom = GUILayout.HorizontalSlider(flowchart.zoom, minZoomValue, maxZoomValue, GUILayout.Width(100)); flowchart.Zoom = GUILayout.HorizontalSlider(flowchart.Zoom, minZoomValue, maxZoomValue, GUILayout.Width(100));
GUILayout.FlexibleSpace(); GUILayout.FlexibleSpace();
GUILayout.BeginVertical(); GUILayout.BeginVertical();
GUILayout.Label(flowchart.name, EditorStyles.whiteBoldLabel); GUILayout.Label(flowchart.name, EditorStyles.whiteBoldLabel);
if (flowchart.description.Length > 0) if (flowchart.Description.Length > 0)
{ {
GUILayout.Label(flowchart.description, EditorStyles.helpBox); GUILayout.Label(flowchart.Description, EditorStyles.helpBox);
} }
GUILayout.EndVertical(); GUILayout.EndVertical();
@ -189,7 +186,7 @@ namespace Fungus
GUILayout.FlexibleSpace(); GUILayout.FlexibleSpace();
flowchart.variablesScrollPos = GUILayout.BeginScrollView(flowchart.variablesScrollPos, GUILayout.MaxHeight(position.height * 0.75f)); flowchart.VariablesScrollPos = GUILayout.BeginScrollView(flowchart.VariablesScrollPos, GUILayout.MaxHeight(position.height * 0.75f));
GUILayout.FlexibleSpace(); GUILayout.FlexibleSpace();
@ -200,8 +197,8 @@ namespace Fungus
DestroyImmediate(flowchartEditor); DestroyImmediate(flowchartEditor);
Rect variableWindowRect = GUILayoutUtility.GetLastRect(); Rect variableWindowRect = GUILayoutUtility.GetLastRect();
if (flowchart.variablesExpanded && if (flowchart.VariablesExpanded &&
flowchart.variables.Count > 0) flowchart.Variables.Count > 0)
{ {
variableWindowRect.y -= 20; variableWindowRect.y -= 20;
variableWindowRect.height += 20; variableWindowRect.height += 20;
@ -226,16 +223,18 @@ namespace Fungus
foreach (Block block in blocks) foreach (Block block in blocks)
{ {
flowchart.scrollViewRect.xMin = Mathf.Min(flowchart.scrollViewRect.xMin, block.nodeRect.xMin - 400); var newRect = new Rect();
flowchart.scrollViewRect.xMax = Mathf.Max(flowchart.scrollViewRect.xMax, block.nodeRect.xMax + 400); newRect.xMin = Mathf.Min(flowchart.ScrollViewRect.xMin, block._NodeRect.xMin - 400);
flowchart.scrollViewRect.yMin = Mathf.Min(flowchart.scrollViewRect.yMin, block.nodeRect.yMin - 400); newRect.xMax = Mathf.Max(flowchart.ScrollViewRect.xMax, block._NodeRect.xMax + 400);
flowchart.scrollViewRect.yMax = Mathf.Max(flowchart.scrollViewRect.yMax, block.nodeRect.yMax + 400); newRect.yMin = Mathf.Min(flowchart.ScrollViewRect.yMin, block._NodeRect.yMin - 400);
newRect.yMax = Mathf.Max(flowchart.ScrollViewRect.yMax, block._NodeRect.yMax + 400);
flowchart.ScrollViewRect = newRect;
} }
// Calc rect for script view // Calc rect for script view
Rect scriptViewRect = new Rect(0, 0, this.position.width / flowchart.zoom, this.position.height / flowchart.zoom); Rect scriptViewRect = new Rect(0, 0, this.position.width / flowchart.Zoom, this.position.height / flowchart.Zoom);
EditorZoomArea.Begin(flowchart.zoom, scriptViewRect); EditorZoomArea.Begin(flowchart.Zoom, scriptViewRect);
DrawGrid(flowchart); DrawGrid(flowchart);
@ -245,7 +244,7 @@ namespace Fungus
Event.current.type == EventType.MouseDown && Event.current.type == EventType.MouseDown &&
!mouseOverVariables) !mouseOverVariables)
{ {
flowchart.selectedBlock = null; flowchart.SelectedBlock = null;
if (!EditorGUI.actionKey) if (!EditorGUI.actionKey)
{ {
flowchart.ClearSelectedCommands(); flowchart.ClearSelectedCommands();
@ -277,46 +276,49 @@ namespace Fungus
{ {
Block block = blocks[i]; Block block = blocks[i];
float nodeWidthA = nodeStyle.CalcSize(new GUIContent(block.blockName)).x + 10; float nodeWidthA = nodeStyle.CalcSize(new GUIContent(block.BlockName)).x + 10;
float nodeWidthB = 0f; float nodeWidthB = 0f;
if (block.eventHandler != null) if (block._EventHandler != null)
{ {
nodeWidthB = nodeStyle.CalcSize(new GUIContent(block.eventHandler.GetSummary())).x + 10; nodeWidthB = nodeStyle.CalcSize(new GUIContent(block._EventHandler.GetSummary())).x + 10;
} }
block.nodeRect.width = Mathf.Max(Mathf.Max(nodeWidthA, nodeWidthB), 120);
block.nodeRect.height = 40;
if (Event.current.button == 0) if (Event.current.button == 0)
{ {
Rect tempRect = block._NodeRect;
tempRect.width = Mathf.Max(Mathf.Max(nodeWidthA, nodeWidthB), 120);
tempRect.height = 40;
if (Event.current.type == EventType.MouseDrag && dragWindowId == i) if (Event.current.type == EventType.MouseDrag && dragWindowId == i)
{ {
block.nodeRect.x += Event.current.delta.x; tempRect.x += Event.current.delta.x;
block.nodeRect.y += Event.current.delta.y; tempRect.y += Event.current.delta.y;
forceRepaintCount = 6; forceRepaintCount = 6;
} }
else if (Event.current.type == EventType.MouseUp && else if (Event.current.type == EventType.MouseUp &&
dragWindowId == i) dragWindowId == i)
{ {
Vector2 newPos = new Vector2(block.nodeRect.x, block.nodeRect.y); Vector2 newPos = new Vector2(tempRect.x, tempRect.y);
block.nodeRect.x = startDragPosition.x; tempRect.x = startDragPosition.x;
block.nodeRect.y = startDragPosition.y; tempRect.y = startDragPosition.y;
Undo.RecordObject(block, "Node Position"); Undo.RecordObject(block, "Node Position");
block.nodeRect.x = newPos.x; tempRect.x = newPos.x;
block.nodeRect.y = newPos.y; tempRect.y = newPos.y;
dragWindowId = -1; dragWindowId = -1;
forceRepaintCount = 6; forceRepaintCount = 6;
} }
block._NodeRect = tempRect;
} }
Rect windowRect = new Rect(block.nodeRect); Rect windowRect = new Rect(block._NodeRect);
windowRect.x += flowchart.scrollPos.x; windowRect.x += flowchart.ScrollPos.x;
windowRect.y += flowchart.scrollPos.y; windowRect.y += flowchart.ScrollPos.y;
GUILayout.Window(i, windowRect, DrawWindow, "", windowStyle); GUILayout.Window(i, windowRect, DrawWindow, "", windowStyle);
@ -330,10 +332,10 @@ namespace Fungus
// Draw Event Handler labels // Draw Event Handler labels
foreach (Block block in blocks) foreach (Block block in blocks)
{ {
if (block.eventHandler != null) if (block._EventHandler != null)
{ {
string handlerLabel = ""; string handlerLabel = "";
EventHandlerInfoAttribute info = EventHandlerEditor.GetEventHandlerInfo(block.eventHandler.GetType()); EventHandlerInfoAttribute info = EventHandlerEditor.GetEventHandlerInfo(block._EventHandler.GetType());
if (info != null) if (info != null)
{ {
handlerLabel = "<" + info.EventHandlerName + "> "; handlerLabel = "<" + info.EventHandlerName + "> ";
@ -345,10 +347,10 @@ namespace Fungus
handlerStyle.margin.bottom = 0; handlerStyle.margin.bottom = 0;
handlerStyle.alignment = TextAnchor.MiddleCenter; handlerStyle.alignment = TextAnchor.MiddleCenter;
Rect rect = new Rect(block.nodeRect); Rect rect = new Rect(block._NodeRect);
rect.height = handlerStyle.CalcHeight(new GUIContent(handlerLabel), block.nodeRect.width); rect.height = handlerStyle.CalcHeight(new GUIContent(handlerLabel), block._NodeRect.width);
rect.x += flowchart.scrollPos.x; rect.x += flowchart.ScrollPos.x;
rect.y += flowchart.scrollPos.y - rect.height; rect.y += flowchart.ScrollPos.y - rect.height;
GUI.Label(rect, handlerLabel, handlerStyle); GUI.Label(rect, handlerLabel, handlerStyle);
} }
@ -362,23 +364,23 @@ namespace Fungus
{ {
if (b.IsExecuting()) if (b.IsExecuting())
{ {
b.executingIconTimer = Time.realtimeSinceStartup + Block.executingIconFadeTime; b.ExecutingIconTimer = Time.realtimeSinceStartup + Block.executingIconFadeTime;
b.activeCommand.executingIconTimer = Time.realtimeSinceStartup + Block.executingIconFadeTime; b.ActiveCommand.ExecutingIconTimer = Time.realtimeSinceStartup + Block.executingIconFadeTime;
forceRepaintCount = 6; forceRepaintCount = 6;
} }
if (b.executingIconTimer > Time.realtimeSinceStartup) if (b.ExecutingIconTimer > Time.realtimeSinceStartup)
{ {
Rect rect = new Rect(b.nodeRect); Rect rect = new Rect(b._NodeRect);
rect.x += flowchart.scrollPos.x - 37; rect.x += flowchart.ScrollPos.x - 37;
rect.y += flowchart.scrollPos.y + 3; rect.y += flowchart.ScrollPos.y + 3;
rect.width = 34; rect.width = 34;
rect.height = 34; rect.height = 34;
if (!b.IsExecuting()) if (!b.IsExecuting())
{ {
float alpha = (b.executingIconTimer - Time.realtimeSinceStartup) / Block.executingIconFadeTime; float alpha = (b.ExecutingIconTimer - Time.realtimeSinceStartup) / Block.executingIconFadeTime;
alpha = Mathf.Clamp01(alpha); alpha = Mathf.Clamp01(alpha);
GUI.color = new Color(1f, 1f, 1f, alpha); GUI.color = new Color(1f, 1f, 1f, alpha);
} }
@ -408,15 +410,15 @@ namespace Fungus
return; return;
} }
Vector2 min = blocks[0].nodeRect.min; Vector2 min = blocks[0]._NodeRect.min;
Vector2 max = blocks[0].nodeRect.max; Vector2 max = blocks[0]._NodeRect.max;
foreach (Block block in blocks) foreach (Block block in blocks)
{ {
min.x = Mathf.Min(min.x, block.nodeRect.center.x); min.x = Mathf.Min(min.x, block._NodeRect.center.x);
min.y = Mathf.Min(min.y, block.nodeRect.center.y); min.y = Mathf.Min(min.y, block._NodeRect.center.y);
max.x = Mathf.Max(max.x, block.nodeRect.center.x); max.x = Mathf.Max(max.x, block._NodeRect.center.x);
max.y = Mathf.Max(max.y, block.nodeRect.center.y); max.y = Mathf.Max(max.y, block._NodeRect.center.y);
} }
Vector2 center = (min + max) * -0.5f; Vector2 center = (min + max) * -0.5f;
@ -424,7 +426,7 @@ namespace Fungus
center.x += position.width * 0.5f; center.x += position.width * 0.5f;
center.y += position.height * 0.5f; center.y += position.height * 0.5f;
flowchart.centerPosition = center; flowchart.CenterPosition = center;
} }
protected virtual void PanAndZoom(Flowchart flowchart) protected virtual void PanAndZoom(Flowchart flowchart)
@ -454,7 +456,7 @@ namespace Fungus
if (drag) if (drag)
{ {
flowchart.scrollPos += Event.current.delta; flowchart.ScrollPos += Event.current.delta;
forceRepaintCount = 6; forceRepaintCount = 6;
} }
@ -475,16 +477,16 @@ namespace Fungus
if (zoom) if (zoom)
{ {
flowchart.zoom -= Event.current.delta.y * 0.01f; flowchart.Zoom -= Event.current.delta.y * 0.01f;
flowchart.zoom = Mathf.Clamp(flowchart.zoom, minZoomValue, maxZoomValue); flowchart.Zoom = Mathf.Clamp(flowchart.Zoom, minZoomValue, maxZoomValue);
forceRepaintCount = 6; forceRepaintCount = 6;
} }
} }
protected virtual void DrawGrid(Flowchart flowchart) protected virtual void DrawGrid(Flowchart flowchart)
{ {
float width = this.position.width / flowchart.zoom; float width = this.position.width / flowchart.Zoom;
float height = this.position.height / flowchart.zoom; float height = this.position.height / flowchart.Zoom;
// Match background color of scene view // Match background color of scene view
if (EditorGUIUtility.isProSkin) if (EditorGUIUtility.isProSkin)
@ -502,14 +504,14 @@ namespace Fungus
float gridSize = 128f; float gridSize = 128f;
float x = flowchart.scrollPos.x % gridSize; float x = flowchart.ScrollPos.x % gridSize;
while (x < width) while (x < width)
{ {
GLDraw.DrawLine(new Vector2(x, 0), new Vector2(x, height), color, 1f); GLDraw.DrawLine(new Vector2(x, 0), new Vector2(x, height), color, 1f);
x += gridSize; x += gridSize;
} }
float y = (flowchart.scrollPos.y % gridSize); float y = (flowchart.ScrollPos.y % gridSize);
while (y < height) while (y < height)
{ {
if (y >= 0) if (y >= 0)
@ -524,11 +526,11 @@ namespace Fungus
{ {
// Select the block and also select currently executing command // Select the block and also select currently executing command
ShowBlockInspector(flowchart); ShowBlockInspector(flowchart);
flowchart.selectedBlock = block; flowchart.SelectedBlock = block;
flowchart.ClearSelectedCommands(); flowchart.ClearSelectedCommands();
if (block.activeCommand != null) if (block.ActiveCommand != null)
{ {
flowchart.AddSelectedCommand(block.activeCommand); flowchart.AddSelectedCommand(block.ActiveCommand);
} }
} }
@ -537,7 +539,7 @@ namespace Fungus
Block newBlock = flowchart.CreateBlock(position); Block newBlock = flowchart.CreateBlock(position);
Undo.RegisterCreatedObjectUndo(newBlock, "New Block"); Undo.RegisterCreatedObjectUndo(newBlock, "New Block");
ShowBlockInspector(flowchart); ShowBlockInspector(flowchart);
flowchart.selectedBlock = newBlock; flowchart.SelectedBlock = newBlock;
flowchart.ClearSelectedCommands(); flowchart.ClearSelectedCommands();
return newBlock; return newBlock;
@ -545,7 +547,7 @@ namespace Fungus
protected virtual void DeleteBlock(Flowchart flowchart, Block block) protected virtual void DeleteBlock(Flowchart flowchart, Block block)
{ {
foreach (Command command in block.commandList) foreach (Command command in block.CommandList)
{ {
Undo.DestroyObjectImmediate(command); Undo.DestroyObjectImmediate(command);
} }
@ -574,8 +576,8 @@ namespace Fungus
Event.current.alt == false) Event.current.alt == false)
{ {
dragWindowId = windowId; dragWindowId = windowId;
startDragPosition.x = block.nodeRect.x; startDragPosition.x = block._NodeRect.x;
startDragPosition.y = block.nodeRect.y; startDragPosition.y = block._NodeRect.y;
} }
if (windowId < windowBlockMap.Count) if (windowId < windowBlockMap.Count)
@ -588,11 +590,11 @@ namespace Fungus
} }
} }
bool selected = (flowchart.selectedBlock == block); bool selected = (flowchart.SelectedBlock == block);
GUIStyle nodeStyleCopy = new GUIStyle(nodeStyle); GUIStyle nodeStyleCopy = new GUIStyle(nodeStyle);
if (block.eventHandler != null) if (block._EventHandler != null)
{ {
nodeStyleCopy.normal.background = selected ? FungusEditorResources.texEventNodeOn : FungusEditorResources.texEventNodeOff; nodeStyleCopy.normal.background = selected ? FungusEditorResources.texEventNodeOn : FungusEditorResources.texEventNodeOff;
} }
@ -624,17 +626,19 @@ namespace Fungus
nodeStyleCopy.normal.textColor = Color.black; nodeStyleCopy.normal.textColor = Color.black;
// Make sure node is wide enough to fit the node name text // Make sure node is wide enough to fit the node name text
float width = nodeStyleCopy.CalcSize(new GUIContent(block.blockName)).x; float width = nodeStyleCopy.CalcSize(new GUIContent(block.BlockName)).x;
block.nodeRect.width = Mathf.Max (block.nodeRect.width, width); Rect tempRect = block._NodeRect;
tempRect.width = Mathf.Max (block._NodeRect.width, width);
block._NodeRect = tempRect;
GUI.backgroundColor = Color.white; GUI.backgroundColor = Color.white;
GUILayout.Box(block.blockName, nodeStyleCopy, GUILayout.Width(block.nodeRect.width), GUILayout.Height(block.nodeRect.height)); GUILayout.Box(block.BlockName, nodeStyleCopy, GUILayout.Width(block._NodeRect.width), GUILayout.Height(block._NodeRect.height));
if (block.description.Length > 0) if (block.Description.Length > 0)
{ {
GUIStyle descriptionStyle = new GUIStyle(EditorStyles.helpBox); GUIStyle descriptionStyle = new GUIStyle(EditorStyles.helpBox);
descriptionStyle.wordWrap = true; descriptionStyle.wordWrap = true;
GUILayout.Label(block.description, descriptionStyle); GUILayout.Label(block.Description, descriptionStyle);
} }
if (Event.current.type == EventType.ContextClick) if (Event.current.type == EventType.ContextClick)
@ -657,9 +661,9 @@ namespace Fungus
List<Block> connectedBlocks = new List<Block>(); List<Block> connectedBlocks = new List<Block>();
bool blockIsSelected = (flowchart.selectedBlock == block); bool blockIsSelected = (flowchart.SelectedBlock == block);
foreach (Command command in block.commandList) foreach (Command command in block.CommandList)
{ {
if (command == null) if (command == null)
{ {
@ -667,7 +671,7 @@ namespace Fungus
} }
bool commandIsSelected = false; bool commandIsSelected = false;
foreach (Command selectedCommand in flowchart.selectedCommands) foreach (Command selectedCommand in flowchart.SelectedCommands)
{ {
if (selectedCommand == command) if (selectedCommand == command)
{ {
@ -676,7 +680,7 @@ namespace Fungus
} }
} }
bool highlight = command.isExecuting || (blockIsSelected && commandIsSelected); bool highlight = command.IsExecuting || (blockIsSelected && commandIsSelected);
if (highlightedOnly && !highlight || if (highlightedOnly && !highlight ||
!highlightedOnly && highlight) !highlightedOnly && highlight)
@ -696,13 +700,13 @@ namespace Fungus
continue; continue;
} }
Rect startRect = new Rect(block.nodeRect); Rect startRect = new Rect(block._NodeRect);
startRect.x += flowchart.scrollPos.x; startRect.x += flowchart.ScrollPos.x;
startRect.y += flowchart.scrollPos.y; startRect.y += flowchart.ScrollPos.y;
Rect endRect = new Rect(blockB.nodeRect); Rect endRect = new Rect(blockB._NodeRect);
endRect.x += flowchart.scrollPos.x; endRect.x += flowchart.ScrollPos.x;
endRect.y += flowchart.scrollPos.y; endRect.y += flowchart.ScrollPos.y;
DrawRectConnection(startRect, endRect, highlight); DrawRectConnection(startRect, endRect, highlight);
} }
@ -769,18 +773,18 @@ namespace Fungus
Flowchart flowchart = GetFlowchart(); Flowchart flowchart = GetFlowchart();
Block block = obj as Block; Block block = obj as Block;
Vector2 newPosition = new Vector2(block.nodeRect.position.x + Vector2 newPosition = new Vector2(block._NodeRect.position.x +
block.nodeRect.width + 20, block._NodeRect.width + 20,
block.nodeRect.y); block._NodeRect.y);
Block oldBlock = block; Block oldBlock = block;
Block newBlock = FlowchartWindow.CreateBlock(flowchart, newPosition); Block newBlock = FlowchartWindow.CreateBlock(flowchart, newPosition);
newBlock.blockName = flowchart.GetUniqueBlockKey(oldBlock.blockName + " (Copy)"); newBlock.BlockName = flowchart.GetUniqueBlockKey(oldBlock.BlockName + " (Copy)");
Undo.RecordObject(newBlock, "Duplicate Block"); Undo.RecordObject(newBlock, "Duplicate Block");
foreach (Command command in oldBlock.commandList) foreach (Command command in oldBlock.CommandList)
{ {
if (ComponentUtility.CopyComponent(command)) if (ComponentUtility.CopyComponent(command))
{ {
@ -790,8 +794,8 @@ namespace Fungus
Command pastedCommand = commands.Last<Command>(); Command pastedCommand = commands.Last<Command>();
if (pastedCommand != null) if (pastedCommand != null)
{ {
pastedCommand.itemId = flowchart.NextItemId(); pastedCommand.ItemId = flowchart.NextItemId();
newBlock.commandList.Add (pastedCommand); newBlock.CommandList.Add (pastedCommand);
} }
} }
@ -800,9 +804,9 @@ namespace Fungus
} }
} }
if (oldBlock.eventHandler != null) if (oldBlock._EventHandler != null)
{ {
if (ComponentUtility.CopyComponent(oldBlock.eventHandler)) if (ComponentUtility.CopyComponent(oldBlock._EventHandler))
{ {
if (ComponentUtility.PasteComponentAsNew(flowchart.gameObject)) if (ComponentUtility.PasteComponentAsNew(flowchart.gameObject))
{ {
@ -810,8 +814,8 @@ namespace Fungus
EventHandler pastedEventHandler = eventHandlers.Last<EventHandler>(); EventHandler pastedEventHandler = eventHandlers.Last<EventHandler>();
if (pastedEventHandler != null) if (pastedEventHandler != null)
{ {
pastedEventHandler.parentBlock = newBlock; pastedEventHandler.ParentBlock = newBlock;
newBlock.eventHandler = pastedEventHandler; newBlock._EventHandler = pastedEventHandler;
} }
} }
} }
@ -833,9 +837,9 @@ namespace Fungus
EditorUtility.SetDirty(blockInspector); EditorUtility.SetDirty(blockInspector);
} }
/** /// <summary>
* Displays a temporary text alert in the center of the Flowchart window. /// Displays a temporary text alert in the center of the Flowchart window.
*/ /// </summary>
public static void ShowNotification(string notificationText) public static void ShowNotification(string notificationText)
{ {
EditorWindow window = EditorWindow.GetWindow(typeof(FlowchartWindow), false, "Flowchart"); EditorWindow window = EditorWindow.GetWindow(typeof(FlowchartWindow), false, "Flowchart");

8
Assets/Fungus/Flowchart/Editor/FungusEditorResources.cs

@ -1,7 +1,5 @@
/** // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
using UnityEngine; using UnityEngine;
using UnityEditor; using UnityEditor;
@ -9,7 +7,6 @@ using System;
namespace Fungus namespace Fungus
{ {
internal static class FungusEditorResources internal static class FungusEditorResources
{ {
@ -187,5 +184,4 @@ namespace Fungus
return (imageData[offset] << 8) | imageData[offset + 1]; return (imageData[offset] << 8) | imageData[offset + 1];
} }
} }
} }

20
Assets/Fungus/Flowchart/Editor/GLDraw.cs

@ -1,26 +1,21 @@
/** // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
using UnityEngine; using UnityEngine;
using System.Collections;
using System;
namespace Fungus namespace Fungus
{ {
/// <summary>
/// Clipping code: http://forum.unity3d.com/threads/17066-How-to-draw-a-GUI-2D-quot-line-quot?p=230386#post230386
/// Thick line drawing code: http://unifycommunity.com/wiki/index.php?title=VectorLine
/// Credit: "http://cs-people.bu.edu/jalon/cs480/Oct11Lab/clip.c"
/// </summary>
public class GLDraw public class GLDraw
{ {
/*
* Clipping code: http://forum.unity3d.com/threads/17066-How-to-draw-a-GUI-2D-quot-line-quot?p=230386#post230386
* Thick line drawing code: http://unifycommunity.com/wiki/index.php?title=VectorLine
*/
protected static bool clippingEnabled; protected static bool clippingEnabled;
protected static Rect clippingBounds; protected static Rect clippingBounds;
public static Material lineMaterial = null; public static Material lineMaterial = null;
/* @ Credit: "http://cs-people.bu.edu/jalon/cs480/Oct11Lab/clip.c" */
protected static bool clip_test(float p, float q, ref float u1, ref float u2) protected static bool clip_test(float p, float q, ref float u1, ref float u2)
{ {
float r; float r;
@ -294,5 +289,4 @@ namespace Fungus
return rt * rt * rt * s + 3 * rt * rtt * st + 3 * rtt * t * et + t * t * t * e; return rt * rt * rt * s + 3 * rt * rtt * st + 3 * rtt * t * et + t * t * t * e;
} }
} }
} }

10
Assets/Fungus/Flowchart/Editor/IfEditor.cs

@ -1,17 +1,12 @@
/** // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
using UnityEditor; using UnityEditor;
using UnityEngine; using UnityEngine;
using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using System.Reflection;
namespace Fungus namespace Fungus
{ {
[CustomEditor (typeof(If), true)] [CustomEditor (typeof(If), true)]
public class IfEditor : CommandEditor public class IfEditor : CommandEditor
{ {
@ -94,5 +89,4 @@ namespace Fungus
serializedObject.ApplyModifiedProperties(); serializedObject.ApplyModifiedProperties();
} }
} }
} }

9
Assets/Fungus/Flowchart/Editor/InvokeEventEditor.cs

@ -1,12 +1,7 @@
/** // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
using UnityEditor; using UnityEditor;
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
namespace Fungus namespace Fungus
{ {

45
Assets/Fungus/Flowchart/Editor/InvokeMethodEditor.cs

@ -1,7 +1,5 @@
/** // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
using UnityEngine; using UnityEngine;
using System.Collections; using System.Collections;
@ -10,11 +8,9 @@ using System.Linq;
using System.Reflection; using System.Reflection;
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Text;
namespace Fungus namespace Fungus
{ {
[CustomEditor(typeof(InvokeMethod))] [CustomEditor(typeof(InvokeMethod))]
public class InvokeMethodEditor : CommandEditor public class InvokeMethodEditor : CommandEditor
{ {
@ -26,23 +22,23 @@ namespace Fungus
targetMethod = target as InvokeMethod; targetMethod = target as InvokeMethod;
if (targetMethod == null || targetMethod.targetObject == null) if (targetMethod == null || targetMethod.TargetObject == null)
return; return;
SerializedObject objSerializedTarget = new SerializedObject(targetMethod); SerializedObject objSerializedTarget = new SerializedObject(targetMethod);
string component = ShowComponents(objSerializedTarget, targetMethod.targetObject); string component = ShowComponents(objSerializedTarget, targetMethod.TargetObject);
// show component methods if selected // show component methods if selected
if (!string.IsNullOrEmpty(component)) if (!string.IsNullOrEmpty(component))
{ {
var method = ShowMethods(objSerializedTarget, targetMethod.targetObject, component); var method = ShowMethods(objSerializedTarget, targetMethod.TargetObject, component);
// show method parameters if selected // show method parameters if selected
if (method != null) if (method != null)
{ {
objSerializedTarget.ApplyModifiedProperties(); objSerializedTarget.ApplyModifiedProperties();
ShowParameters(objSerializedTarget, targetMethod.targetObject, method); ShowParameters(objSerializedTarget, targetMethod.TargetObject, method);
ShowReturnValue(objSerializedTarget, method); ShowReturnValue(objSerializedTarget, method);
} }
} }
@ -172,7 +168,7 @@ namespace Fungus
if (isDrawn) if (isDrawn)
{ {
var vars = GetFungusVariablesByType(targetMethod.GetFlowchart().variables, objParam.ParameterType); var vars = GetFungusVariablesByType(targetMethod.GetFlowchart().Variables, objParam.ParameterType);
var values = new string[] { "<Value>" }; var values = new string[] { "<Value>" };
var displayValue = values.Concat(vars).ToList(); var displayValue = values.Concat(vars).ToList();
@ -241,7 +237,7 @@ namespace Fungus
if (saveReturnValueProp.boolValue) if (saveReturnValueProp.boolValue)
{ {
var vars = GetFungusVariablesByType(targetMethod.GetFlowchart().variables, method.ReturnType).ToList(); var vars = GetFungusVariablesByType(targetMethod.GetFlowchart().Variables, method.ReturnType).ToList();
int index = vars.IndexOf(returnValueKeyProp.stringValue); int index = vars.IndexOf(returnValueKeyProp.stringValue);
index = EditorGUILayout.Popup(method.ReturnType.Name, index, vars.ToArray()); index = EditorGUILayout.Popup(method.ReturnType.Name, index, vars.ToArray());
@ -367,51 +363,51 @@ namespace Fungus
if (type == typeof(int)) if (type == typeof(int))
{ {
result = (from v in variables where v.GetType() == typeof(IntegerVariable) select v.key).ToArray(); result = (from v in variables where v.GetType() == typeof(IntegerVariable) select v.Key).ToArray();
} }
else if (type == typeof(bool)) else if (type == typeof(bool))
{ {
result = (from v in variables where v.GetType() == typeof(BooleanVariable) select v.key).ToArray(); result = (from v in variables where v.GetType() == typeof(BooleanVariable) select v.Key).ToArray();
} }
else if (type == typeof(float)) else if (type == typeof(float))
{ {
result = (from v in variables where v.GetType() == typeof(FloatVariable) select v.key).ToArray(); result = (from v in variables where v.GetType() == typeof(FloatVariable) select v.Key).ToArray();
} }
else if (type == typeof(string)) else if (type == typeof(string))
{ {
result = (from v in variables where v.GetType() == typeof(StringVariable) select v.key).ToArray(); result = (from v in variables where v.GetType() == typeof(StringVariable) select v.Key).ToArray();
} }
else if (type == typeof(Color)) else if (type == typeof(Color))
{ {
result = (from v in variables where v.GetType() == typeof(ColorVariable) select v.key).ToArray(); result = (from v in variables where v.GetType() == typeof(ColorVariable) select v.Key).ToArray();
} }
else if (type == typeof(UnityEngine.GameObject)) else if (type == typeof(UnityEngine.GameObject))
{ {
result = (from v in variables where v.GetType() == typeof(GameObjectVariable) select v.key).ToArray(); result = (from v in variables where v.GetType() == typeof(GameObjectVariable) select v.Key).ToArray();
} }
else if (type == typeof(UnityEngine.Material)) else if (type == typeof(UnityEngine.Material))
{ {
result = (from v in variables where v.GetType() == typeof(MaterialVariable) select v.key).ToArray(); result = (from v in variables where v.GetType() == typeof(MaterialVariable) select v.Key).ToArray();
} }
else if (type == typeof(UnityEngine.Sprite)) else if (type == typeof(UnityEngine.Sprite))
{ {
result = (from v in variables where v.GetType() == typeof(SpriteVariable) select v.key).ToArray(); result = (from v in variables where v.GetType() == typeof(SpriteVariable) select v.Key).ToArray();
} }
else if (type == typeof(UnityEngine.Texture)) else if (type == typeof(UnityEngine.Texture))
{ {
result = (from v in variables where v.GetType() == typeof(TextureVariable) select v.key).ToArray(); result = (from v in variables where v.GetType() == typeof(TextureVariable) select v.Key).ToArray();
} }
else if (type == typeof(UnityEngine.Vector2)) else if (type == typeof(UnityEngine.Vector2))
{ {
result = (from v in variables where v.GetType() == typeof(Vector2Variable) select v.key).ToArray(); result = (from v in variables where v.GetType() == typeof(Vector2Variable) select v.Key).ToArray();
} }
else if (type == typeof(UnityEngine.Vector3)) else if (type == typeof(UnityEngine.Vector3))
{ {
result = (from v in variables where v.GetType() == typeof(Vector3Variable) select v.key).ToArray(); result = (from v in variables where v.GetType() == typeof(Vector3Variable) select v.Key).ToArray();
} }
else if (type.IsSubclassOf(typeof(UnityEngine.Object))) else if (type.IsSubclassOf(typeof(UnityEngine.Object)))
{ {
result = (from v in variables where v.GetType() == typeof(ObjectVariable) select v.key).ToArray(); result = (from v in variables where v.GetType() == typeof(ObjectVariable) select v.Key).ToArray();
} }
return result; return result;
@ -443,5 +439,4 @@ namespace Fungus
return null; return null;
} }
} }
} }

17
Assets/Fungus/Flowchart/Editor/LabelEditor.cs

@ -1,15 +1,9 @@
/** // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
using UnityEditor; using UnityEditor;
using UnityEditorInternal;
using UnityEngine; using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq;
namespace Fungus namespace Fungus
{ {
@ -32,7 +26,7 @@ namespace Fungus
int index = 0; int index = 0;
int selectedIndex = 0; int selectedIndex = 0;
foreach (Command command in block.commandList) foreach (Command command in block.CommandList)
{ {
Label label = command as Label; Label label = command as Label;
if (label == null) if (label == null)
@ -40,7 +34,7 @@ namespace Fungus
continue; continue;
} }
labelKeys.Add(label.key); labelKeys.Add(label.Key);
labelObjects.Add(label); labelObjects.Add(label);
index++; index++;
@ -81,6 +75,5 @@ namespace Fungus
serializedObject.ApplyModifiedProperties(); serializedObject.ApplyModifiedProperties();
} }
} }
} }

10
Assets/Fungus/Flowchart/Editor/SetVariableEditor.cs

@ -1,11 +1,8 @@
/** // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
using UnityEditor; using UnityEditor;
using UnityEngine; using UnityEngine;
using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
namespace Fungus namespace Fungus
@ -73,7 +70,7 @@ namespace Fungus
} }
int selectedIndex = 0; int selectedIndex = 0;
switch (t.setOperator) switch (t._SetOperator)
{ {
default: default:
case SetVariable.SetOperator.Assign: case SetVariable.SetOperator.Assign:
@ -159,5 +156,4 @@ namespace Fungus
serializedObject.ApplyModifiedProperties(); serializedObject.ApplyModifiedProperties();
} }
} }
} }

16
Assets/Fungus/Flowchart/Editor/VariableEditor.cs

@ -1,13 +1,9 @@
/** // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
using UnityEditor; using UnityEditor;
using UnityEditorInternal;
using UnityEngine; using UnityEngine;
using System; using System;
using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
@ -50,7 +46,7 @@ namespace Fungus
variableKeys.Add(defaultText); variableKeys.Add(defaultText);
variableObjects.Add(null); variableObjects.Add(null);
List<Variable> variables = flowchart.variables; List<Variable> variables = flowchart.Variables;
int index = 0; int index = 0;
int selectedIndex = 0; int selectedIndex = 0;
@ -63,7 +59,7 @@ namespace Fungus
// occurs we just skip displaying the property for this frame. // occurs we just skip displaying the property for this frame.
if (selectedVariable != null && if (selectedVariable != null &&
selectedVariable.gameObject != flowchart.gameObject && selectedVariable.gameObject != flowchart.gameObject &&
selectedVariable.scope == VariableScope.Private) selectedVariable.Scope == VariableScope.Private)
{ {
property.objectReferenceValue = null; property.objectReferenceValue = null;
return; return;
@ -79,7 +75,7 @@ namespace Fungus
} }
} }
variableKeys.Add(v.key); variableKeys.Add(v.Key);
variableObjects.Add(v); variableObjects.Add(v);
index++; index++;
@ -109,7 +105,7 @@ namespace Fungus
} }
} }
variableKeys.Add(fs.name + " / " + v.key); variableKeys.Add(fs.name + " / " + v.Key);
variableObjects.Add(v); variableObjects.Add(v);
index++; index++;

24
Assets/Fungus/Flowchart/Editor/VariableListAdaptor.cs

@ -1,7 +1,5 @@
/** // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
// Copyright (c) 2012-2013 Rotorz Limited. All rights reserved. // Copyright (c) 2012-2013 Rotorz Limited. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be // Use of this source code is governed by a BSD-style license that can be
@ -133,15 +131,15 @@ namespace Fungus
// Highlight if an active or selected command is referencing this variable // Highlight if an active or selected command is referencing this variable
bool highlight = false; bool highlight = false;
if (flowchart.selectedBlock != null) if (flowchart.SelectedBlock != null)
{ {
if (Application.isPlaying && flowchart.selectedBlock.IsExecuting()) if (Application.isPlaying && flowchart.SelectedBlock.IsExecuting())
{ {
highlight = flowchart.selectedBlock.activeCommand.HasReference(variable); highlight = flowchart.SelectedBlock.ActiveCommand.HasReference(variable);
} }
else if (!Application.isPlaying && flowchart.selectedCommands.Count > 0) else if (!Application.isPlaying && flowchart.SelectedCommands.Count > 0)
{ {
foreach (Command selectedCommand in flowchart.selectedCommands) foreach (Command selectedCommand in flowchart.SelectedCommands)
{ {
if (selectedCommand == null) if (selectedCommand == null)
{ {
@ -163,8 +161,8 @@ namespace Fungus
GUI.Box(position, ""); GUI.Box(position, "");
} }
string key = variable.key; string key = variable.Key;
VariableScope scope = variable.scope; VariableScope scope = variable.Scope;
// To access properties in a monobehavior, you have to new a SerializedObject // To access properties in a monobehavior, you have to new a SerializedObject
// http://answers.unity3d.com/questions/629803/findrelativeproperty-never-worked-for-me-how-does.html // http://answers.unity3d.com/questions/629803/findrelativeproperty-never-worked-for-me-how-does.html
@ -174,7 +172,7 @@ namespace Fungus
GUI.Label(rects[0], variableInfo.VariableType); GUI.Label(rects[0], variableInfo.VariableType);
key = EditorGUI.TextField(rects[1], variable.key); key = EditorGUI.TextField(rects[1], variable.Key);
SerializedProperty keyProp = variableObject.FindProperty("key"); SerializedProperty keyProp = variableObject.FindProperty("key");
keyProp.stringValue = flowchart.GetUniqueVariableKey(key, variable); keyProp.stringValue = flowchart.GetUniqueVariableKey(key, variable);
@ -182,7 +180,7 @@ namespace Fungus
EditorGUI.PropertyField(rects[2], defaultProp, new GUIContent("")); EditorGUI.PropertyField(rects[2], defaultProp, new GUIContent(""));
SerializedProperty scopeProp = variableObject.FindProperty("scope"); SerializedProperty scopeProp = variableObject.FindProperty("scope");
scope = (VariableScope)EditorGUI.EnumPopup(rects[3], variable.scope); scope = (VariableScope)EditorGUI.EnumPopup(rects[3], variable.Scope);
scopeProp.enumValueIndex = (int)scope; scopeProp.enumValueIndex = (int)scope;
variableObject.ApplyModifiedProperties(); variableObject.ApplyModifiedProperties();

157
Assets/Fungus/Flowchart/Scripts/Block.cs

@ -1,7 +1,5 @@
/** // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
using UnityEngine; using UnityEngine;
using UnityEngine.Serialization; using UnityEngine.Serialization;
@ -11,6 +9,9 @@ using System.Collections.Generic;
namespace Fungus namespace Fungus
{ {
/// <summary>
/// A container for a sequence of Fungus comands.
/// </summary>
[ExecuteInEditMode] [ExecuteInEditMode]
[RequireComponent(typeof(Flowchart))] [RequireComponent(typeof(Flowchart))]
[AddComponentMenu("")] [AddComponentMenu("")]
@ -22,52 +23,72 @@ namespace Fungus
Executing, Executing,
} }
[NonSerialized] /// <summary>
public ExecutionState executionState; /// The execution state of the Block.
/// </summary>
protected ExecutionState executionState;
public ExecutionState State { get { return executionState; } }
[HideInInspector] /// <summary>
public int itemId = -1; // Invalid flowchart item id /// Unique identifier for the Block.
/// </summary>
[SerializeField] protected int itemId = -1; // Invalid flowchart item id
public int ItemId { get { return itemId; } set { itemId = value; } }
/// <summary>
/// The name of the block node as displayed in the Flowchart window.
/// </summary>
[FormerlySerializedAs("sequenceName")] [FormerlySerializedAs("sequenceName")]
[Tooltip("The name of the block node as displayed in the Flowchart window")] [Tooltip("The name of the block node as displayed in the Flowchart window")]
public string blockName = "New Block"; [SerializeField] protected string blockName = "New Block";
public string BlockName { get { return blockName; } set { blockName = value; } }
/// <summary>
/// Description text to display under the block node
/// </summary>
[TextArea(2, 5)] [TextArea(2, 5)]
[Tooltip("Description text to display under the block node")] [Tooltip("Description text to display under the block node")]
public string description = ""; [SerializeField] protected string description = "";
public string Description { get { return description; } }
/// <summary>
/// An optional Event Handler which can execute the block when an event occurs.
/// </summary>
[Tooltip("An optional Event Handler which can execute the block when an event occurs")] [Tooltip("An optional Event Handler which can execute the block when an event occurs")]
public EventHandler eventHandler; [SerializeField] protected EventHandler eventHandler;
public EventHandler _EventHandler { get { return eventHandler; } set { eventHandler = value; } }
[HideInInspector]
[System.NonSerialized]
public Command activeCommand;
// Index of last command executed before the current one /// <summary>
// -1 indicates no previous command /// The currently executing command.
[HideInInspector] /// </summary>
[System.NonSerialized] protected Command activeCommand;
public int previousActiveCommandIndex = -1; public Command ActiveCommand { get { return activeCommand; } }
[HideInInspector] /// <summary>
[System.NonSerialized] // Index of last command executed before the current one.
public float executingIconTimer; // -1 indicates no previous command.
/// </summary>
protected int previousActiveCommandIndex = -1;
public float ExecutingIconTimer { get; set; }
[HideInInspector] /// <summary>
public List<Command> commandList = new List<Command>(); /// The list of commands in the sequence.
/// </summary>
[SerializeField] protected List<Command> commandList = new List<Command>();
public List<Command> CommandList { get { return commandList; } }
protected int executionCount; /// <summary>
/// Controls the next command to execute in the block execution coroutine.
/// </summary>
protected int jumpToCommandIndex = -1;
public int JumpToCommandIndex { set { jumpToCommandIndex = value; } }
/** /// <summary>
* Duration of fade for executing icon displayed beside blocks & commands. /// Duration of fade for executing icon displayed beside blocks & commands.
*/ /// </summary>
public const float executingIconFadeTime = 0.5f; public const float executingIconFadeTime = 0.5f;
/** protected int executionCount;
* Controls the next command to execute in the block execution coroutine.
*/
[NonSerialized]
public int jumpToCommandIndex = -1;
protected bool executionInfoSet = false; protected bool executionInfoSet = false;
@ -76,6 +97,9 @@ namespace Fungus
SetExecutionInfo(); SetExecutionInfo();
} }
/// <summary>
/// Populate the command metadata used to control execution.
/// </summary>
protected virtual void SetExecutionInfo() protected virtual void SetExecutionInfo()
{ {
// Give each child command a reference back to its parent block // Give each child command a reference back to its parent block
@ -88,8 +112,8 @@ namespace Fungus
continue; continue;
} }
command.parentBlock = this; command.ParentBlock = this;
command.commandIndex = index++; command.CommandIndex = index++;
} }
// Ensure all commands are at their correct indent level // Ensure all commands are at their correct indent level
@ -114,34 +138,30 @@ namespace Fungus
continue; continue;
} }
command.commandIndex = index++; command.CommandIndex = index++;
} }
} }
#endif #endif
/// <summary>
/// Returns the parent Flowchart for this Block.
/// </summary>
public virtual Flowchart GetFlowchart() public virtual Flowchart GetFlowchart()
{ {
return GetComponent<Flowchart>(); return GetComponent<Flowchart>();
} }
public virtual bool HasError() /// <summary>
{ /// Returns true if the Block is executing a command.
foreach (Command command in commandList) /// </summary>
{
if (command.errorMessage.Length > 0)
{
return true;
}
}
return false;
}
public virtual bool IsExecuting() public virtual bool IsExecuting()
{ {
return (executionState == ExecutionState.Executing); return (executionState == ExecutionState.Executing);
} }
/// <summary>
/// Returns the number of times this Block has executed.
/// </summary>
public virtual int GetExecutionCount() public virtual int GetExecutionCount()
{ {
return executionCount; return executionCount;
@ -179,7 +199,7 @@ namespace Fungus
#if UNITY_EDITOR #if UNITY_EDITOR
// Select the executing block & the first command // Select the executing block & the first command
flowchart.selectedBlock = this; flowchart.SelectedBlock = this;
if (commandList.Count > 0) if (commandList.Count > 0)
{ {
flowchart.ClearSelectedCommands(); flowchart.ClearSelectedCommands();
@ -205,7 +225,7 @@ namespace Fungus
commandList[i].GetType() == typeof(Comment) || commandList[i].GetType() == typeof(Comment) ||
commandList[i].GetType() == typeof(Label))) commandList[i].GetType() == typeof(Label)))
{ {
i = commandList[i].commandIndex + 1; i = commandList[i].CommandIndex + 1;
} }
if (i >= commandList.Count) if (i >= commandList.Count)
@ -220,7 +240,7 @@ namespace Fungus
} }
else else
{ {
previousActiveCommandIndex = activeCommand.commandIndex; previousActiveCommandIndex = activeCommand.CommandIndex;
} }
Command command = commandList[i]; Command command = commandList[i];
@ -229,18 +249,18 @@ namespace Fungus
if (flowchart.gameObject.activeInHierarchy) if (flowchart.gameObject.activeInHierarchy)
{ {
// Auto select a command in some situations // Auto select a command in some situations
if ((flowchart.selectedCommands.Count == 0 && i == 0) || if ((flowchart.SelectedCommands.Count == 0 && i == 0) ||
(flowchart.selectedCommands.Count == 1 && flowchart.selectedCommands[0].commandIndex == previousActiveCommandIndex)) (flowchart.SelectedCommands.Count == 1 && flowchart.SelectedCommands[0].CommandIndex == previousActiveCommandIndex))
{ {
flowchart.ClearSelectedCommands(); flowchart.ClearSelectedCommands();
flowchart.AddSelectedCommand(commandList[i]); flowchart.AddSelectedCommand(commandList[i]);
} }
} }
command.isExecuting = true; command.IsExecuting = true;
// This icon timer is managed by the FlowchartWindow class, but we also need to // This icon timer is managed by the FlowchartWindow class, but we also need to
// set it here in case a command starts and finishes execution before the next window update. // set it here in case a command starts and finishes execution before the next window update.
command.executingIconTimer = Time.realtimeSinceStartup + executingIconFadeTime; command.ExecutingIconTimer = Time.realtimeSinceStartup + executingIconFadeTime;
command.Execute(); command.Execute();
// Wait until the executing command sets another command to jump to via Command.Continue() // Wait until the executing command sets another command to jump to via Command.Continue()
@ -250,13 +270,13 @@ namespace Fungus
} }
#if UNITY_EDITOR #if UNITY_EDITOR
if (flowchart.stepPause > 0f) if (flowchart.StepPause > 0f)
{ {
yield return new WaitForSeconds(flowchart.stepPause); yield return new WaitForSeconds(flowchart.StepPause);
} }
#endif #endif
command.isExecuting = false; command.IsExecuting = false;
} }
executionState = ExecutionState.Idle; executionState = ExecutionState.Idle;
@ -268,12 +288,15 @@ namespace Fungus
} }
} }
/// <summary>
/// Stop executing commands in this Block.
/// </summary>
public virtual void Stop() public virtual void Stop()
{ {
// Tell the executing command to stop immediately // Tell the executing command to stop immediately
if (activeCommand != null) if (activeCommand != null)
{ {
activeCommand.isExecuting = false; activeCommand.IsExecuting = false;
activeCommand.OnStopExecuting(); activeCommand.OnStopExecuting();
} }
@ -281,6 +304,9 @@ namespace Fungus
jumpToCommandIndex = int.MaxValue; jumpToCommandIndex = int.MaxValue;
} }
/// <summary>
/// Returns a list of all Blocks connected to this one.
/// </summary>
public virtual List<Block> GetConnectedBlocks() public virtual List<Block> GetConnectedBlocks()
{ {
List<Block> connectedBlocks = new List<Block>(); List<Block> connectedBlocks = new List<Block>();
@ -294,6 +320,10 @@ namespace Fungus
return connectedBlocks; return connectedBlocks;
} }
/// <summary>
/// Returns the type of the previously executing command.
/// </summary>
/// <returns>The previous active command type.</returns>
public virtual System.Type GetPreviousActiveCommandType() public virtual System.Type GetPreviousActiveCommandType()
{ {
if (previousActiveCommandIndex >= 0 && if (previousActiveCommandIndex >= 0 &&
@ -305,6 +335,9 @@ namespace Fungus
return null; return null;
} }
/// <summary>
/// Recalculate the indent levels for all commands in the list.
/// </summary>
public virtual void UpdateIndentLevels() public virtual void UpdateIndentLevels()
{ {
int indentLevel = 0; int indentLevel = 0;
@ -323,7 +356,7 @@ namespace Fungus
// Negative indent level is not permitted // Negative indent level is not permitted
indentLevel = Math.Max(indentLevel, 0); indentLevel = Math.Max(indentLevel, 0);
command.indentLevel = indentLevel; command.IndentLevel = indentLevel;
if (command.OpenBlock()) if (command.OpenBlock())
{ {

221
Assets/Fungus/Flowchart/Scripts/Command.cs

@ -1,26 +1,25 @@
/** // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
using UnityEngine; using UnityEngine;
using UnityEngine.Serialization; using UnityEngine.Serialization;
using System; using System;
using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
namespace Fungus namespace Fungus
{ {
/// <summary>
/// Attribute class for Fungus commands.
/// </summary>
public class CommandInfoAttribute : Attribute public class CommandInfoAttribute : Attribute
{ {
/** /// <summary>
* Metadata atribute for the Command class. /// Metadata atribute for the Command class.
* @param category The category to place this command in. /// </summary>
* @param commandName The display name of the command. /// <param name="category">The category to place this command in.</param>
* @param helpText Help information to display in the inspector. /// <param name="commandName">The display name of the command.</param>
* @param priority If two command classes have the same name, the one with highest priority is listed. Negative priority removess the command from the list. /// <param name="helpText">Help information to display in the inspector.</param>
*/ /// <param name="priority">If two command classes have the same name, the one with highest priority is listed. Negative priority removess the command from the list.</param>///
public CommandInfoAttribute(string category, string commandName, string helpText, int priority = 0) public CommandInfoAttribute(string category, string commandName, string helpText, int priority = 0)
{ {
this.Category = category; this.Category = category;
@ -35,41 +34,59 @@ namespace Fungus
public int Priority { get; set; } public int Priority { get; set; }
} }
/// <summary>
/// Base class for Commands. Commands can be added to Blocks to create an execution sequence.
/// </summary>
public class Command : MonoBehaviour public class Command : MonoBehaviour
{ {
/// <summary>
/// Unique identifier for this command.
/// Unique for this Flowchart.
/// </summary>
[FormerlySerializedAs("commandId")] [FormerlySerializedAs("commandId")]
[HideInInspector] [HideInInspector]
public int itemId = -1; // Invalid flowchart item id [SerializeField] protected int itemId = -1; // Invalid flowchart item id
public int ItemId { get { return itemId; } set { itemId = value; } }
[HideInInspector]
public string errorMessage = ""; /// <summary>
/// Error message to display in the command inspector.
/// </summary>
protected string errorMessage = "";
public string ErrorMessage { get { return errorMessage; } }
/// <summary>
/// Indent depth of the current commands.
/// Commands are indented inside If, While, etc. sections.
/// </summary>
[HideInInspector] [HideInInspector]
public int indentLevel; [SerializeField] protected int indentLevel;
public int IndentLevel { get { return indentLevel; } set { indentLevel = value; } }
[NonSerialized]
public int commandIndex; /// <summary>
/// Index of the command in the parent block's command list.
/** /// </summary>
* Set to true by the parent block while the command is executing. public int CommandIndex { get; set; }
*/
[NonSerialized] /// <summary>
public bool isExecuting; /// Set to true by the parent block while the command is executing.
/// </summary>
/** public bool IsExecuting { get; set; }
* Timer used to control appearance of executing icon in inspector.
*/ /// <summary>
[NonSerialized] /// Timer used to control appearance of executing icon in inspector.
public float executingIconTimer; /// </summary>
public float ExecutingIconTimer { get; set; }
/**
* Reference to the Block object that this command belongs to. /// <summary>
* This reference is only populated at runtime and in the editor when the /// Reference to the Block object that this command belongs to.
* block is selected. /// This reference is only populated at runtime and in the editor when the
*/ /// block is selected.
[NonSerialized] /// </summary>
public Block parentBlock; public Block ParentBlock { get; set; }
/// <summary>
/// Returns the Flowchart that this command belongs to.
/// </summary>
public virtual Flowchart GetFlowchart() public virtual Flowchart GetFlowchart()
{ {
Flowchart flowchart = GetComponent<Flowchart>(); Flowchart flowchart = GetComponent<Flowchart>();
@ -81,131 +98,167 @@ namespace Fungus
return flowchart; return flowchart;
} }
/// <summary>
/// Execute the command.
/// </summary>
public virtual void Execute() public virtual void Execute()
{ {
OnEnter(); OnEnter();
} }
/// <summary>
/// End execution of this command and continue execution at the next command.
/// </summary>
public virtual void Continue() public virtual void Continue()
{ {
// This is a noop if the Block has already been stopped // This is a noop if the Block has already been stopped
if (isExecuting) if (IsExecuting)
{ {
Continue(commandIndex + 1); Continue(CommandIndex + 1);
} }
} }
/// <summary>
/// End execution of this command and continue execution at a specific command index.
/// </summary>
/// <param name="nextCommandIndex">Next command index.</param>
public virtual void Continue(int nextCommandIndex) public virtual void Continue(int nextCommandIndex)
{ {
OnExit(); OnExit();
if (parentBlock != null) if (ParentBlock != null)
{ {
parentBlock.jumpToCommandIndex = nextCommandIndex; ParentBlock.JumpToCommandIndex = nextCommandIndex;
} }
} }
/// <summary>
/// Stops the parent Block executing.
/// </summary>
public virtual void StopParentBlock() public virtual void StopParentBlock()
{ {
OnExit(); OnExit();
if (parentBlock != null) if (ParentBlock != null)
{ {
parentBlock.Stop(); ParentBlock.Stop();
} }
} }
/** /// <summary>
* Called when the parent block has been requested to stop executing, and /// Called when the parent block has been requested to stop executing, and
* this command is the currently executing command. /// this command is the currently executing command.
* Use this callback to terminate any asynchronous operations and /// Use this callback to terminate any asynchronous operations and
* cleanup state so that the command is ready to execute again later on. /// cleanup state so that the command is ready to execute again later on.
*/ /// </summary>
public virtual void OnStopExecuting() public virtual void OnStopExecuting()
{} {}
/** /// <summary>
* Called when the new command is added to a block in the editor. /// Called when the new command is added to a block in the editor.
*/ /// </summary>
public virtual void OnCommandAdded(Block parentBlock) public virtual void OnCommandAdded(Block parentBlock)
{} {}
/** /// <summary>
* Called when the command is deleted from a block in the editor. /// Called when the command is deleted from a block in the editor.
*/ /// </summary>
public virtual void OnCommandRemoved(Block parentBlock) public virtual void OnCommandRemoved(Block parentBlock)
{} {}
/// <summary>
/// Called when this command starts execution.
/// </summary>
public virtual void OnEnter() public virtual void OnEnter()
{} {}
/// <summary>
/// Called when this command ends execution.
/// </summary>
public virtual void OnExit() public virtual void OnExit()
{} {}
/// <summary>
/// Called when this command is reset. This happens when the Reset command is used.
/// </summary>
public virtual void OnReset() public virtual void OnReset()
{} {}
/// <summary>
/// Populates a list with the Blocks that this command references.
/// </summary>
public virtual void GetConnectedBlocks(ref List<Block> connectedBlocks) public virtual void GetConnectedBlocks(ref List<Block> connectedBlocks)
{} {}
/// <summary>
/// Returns true if this command references the variable.
/// Used to highlight variables in the variable list when a command is selected.
/// </summary>
public virtual bool HasReference(Variable variable) public virtual bool HasReference(Variable variable)
{ {
return false; return false;
} }
/// <summary>
/// Returns the summary text to display in the command inspector.
/// </summary>
public virtual string GetSummary() public virtual string GetSummary()
{ {
return ""; return "";
} }
/// <summary>
/// Returns the help text to display for this command.
/// </summary>
public virtual string GetHelpText() public virtual string GetHelpText()
{ {
return ""; return "";
} }
/** /// <summary>
* This command starts a block of commands. /// Return true if this command opens a block of commands. Used for indenting commands.
*/ /// </summary>
public virtual bool OpenBlock() public virtual bool OpenBlock()
{ {
return false; return false;
} }
/** /// <summary>
* This command ends a block of commands. /// Return true if this command closes a block of commands. Used for indenting commands.
*/ /// </summary>
public virtual bool CloseBlock() public virtual bool CloseBlock()
{ {
return false; return false;
} }
/** /// <summary>
* Return the color for the command background in inspector. /// Return the color for the command background in inspector.
*/ /// </summary>
/// <returns>The button color.</returns>
public virtual Color GetButtonColor() public virtual Color GetButtonColor()
{ {
return Color.white; return Color.white;
} }
/** /// <summary>
* Returns true if the specified property should be displayed in the inspector. /// Returns true if the specified property should be displayed in the inspector.
* This is useful for hiding certain properties based on the value of another property. /// This is useful for hiding certain properties based on the value of another property.
*/ /// </summary>
public virtual bool IsPropertyVisible(string propertyName) public virtual bool IsPropertyVisible(string propertyName)
{ {
return true; return true;
} }
/** /// <summary>
* Returns true if the specified property should be displayed as a reorderable list in the inspector. /// Returns true if the specified property should be displayed as a reorderable list in the inspector.
* This only applies for array properties and has no effect for non-array properties. /// This only applies for array properties and has no effect for non-array properties.
*/ /// </summary>
public virtual bool IsReorderableArray(string propertyName) public virtual bool IsReorderableArray(string propertyName)
{ {
return false; return false;
} }
/** /// <summary>
* Returns the localization id for the Flowchart that contains this command. /// Returns the localization id for the Flowchart that contains this command.
*/ /// </summary>
public virtual string GetFlowchartLocalizationId() public virtual string GetFlowchartLocalizationId()
{ {
// If no localization id has been set then use the Flowchart name // If no localization id has been set then use the Flowchart name
@ -215,7 +268,7 @@ namespace Fungus
return ""; return "";
} }
string localizationId = GetFlowchart().localizationId; string localizationId = GetFlowchart().LocalizationId;
if (localizationId.Length == 0) if (localizationId.Length == 0)
{ {
localizationId = flowchart.name; localizationId = flowchart.name;
@ -223,7 +276,5 @@ namespace Fungus
return localizationId; return localizationId;
} }
} }
} }

20
Assets/Fungus/Flowchart/Scripts/CommandCopyBuffer.cs

@ -1,23 +1,22 @@
/** // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
using UnityEngine; using UnityEngine;
using System.Collections;
namespace Fungus namespace Fungus
{ {
/// <summary>
/// Temporary buffer object used when copying and pasting commands.
/// </summary>
[AddComponentMenu("")] [AddComponentMenu("")]
public class CommandCopyBuffer : Block public class CommandCopyBuffer : Block
{ {
protected static CommandCopyBuffer instance; protected static CommandCopyBuffer instance;
/** /// <summary>
* Returns the CommandCopyBuffer singleton instance. /// Returns the CommandCopyBuffer singleton instance.
* Will create a CommandCopyBuffer game object if none currently exists. /// Will create a CommandCopyBuffer game object if none currently exists.
*/ /// </summary>
static public CommandCopyBuffer GetInstance() static public CommandCopyBuffer GetInstance()
{ {
if (instance == null) if (instance == null)
@ -67,5 +66,4 @@ namespace Fungus
} }
} }
} }
} }

31
Assets/Fungus/Flowchart/Scripts/Commands/Break.cs

@ -1,15 +1,13 @@
/** // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
using UnityEngine; using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
namespace Fungus namespace Fungus
{ {
/// <summary>
/// Force a loop to terminate immediately.
/// </summary>
[CommandInfo("Flow", [CommandInfo("Flow",
"Break", "Break",
"Force a loop to terminate immediately.")] "Force a loop to terminate immediately.")]
@ -21,13 +19,13 @@ namespace Fungus
// Find index of previous while command // Find index of previous while command
int whileIndex = -1; int whileIndex = -1;
int whileIndentLevel = -1; int whileIndentLevel = -1;
for (int i = commandIndex - 1; i >=0; --i) for (int i = CommandIndex - 1; i >=0; --i)
{ {
While whileCommand = parentBlock.commandList[i] as While; While whileCommand = ParentBlock.CommandList[i] as While;
if (whileCommand != null) if (whileCommand != null)
{ {
whileIndex = i; whileIndex = i;
whileIndentLevel = whileCommand.indentLevel; whileIndentLevel = whileCommand.IndentLevel;
break; break;
} }
} }
@ -40,18 +38,18 @@ namespace Fungus
} }
// Find matching End statement at same indent level as While // Find matching End statement at same indent level as While
for (int i = whileIndex + 1; i < parentBlock.commandList.Count; ++i) for (int i = whileIndex + 1; i < ParentBlock.CommandList.Count; ++i)
{ {
End endCommand = parentBlock.commandList[i] as End; End endCommand = ParentBlock.CommandList[i] as End;
if (endCommand != null && if (endCommand != null &&
endCommand.indentLevel == whileIndentLevel) endCommand.IndentLevel == whileIndentLevel)
{ {
// Sanity check that break command is actually between the While and End commands // Sanity check that break command is actually between the While and End commands
if (commandIndex > whileIndex && commandIndex < endCommand.commandIndex) if (CommandIndex > whileIndex && CommandIndex < endCommand.CommandIndex)
{ {
// Continue at next command after End // Continue at next command after End
Continue (endCommand.commandIndex + 1); Continue (endCommand.CommandIndex + 1);
return; return;
} }
else else
@ -69,6 +67,5 @@ namespace Fungus
{ {
return new Color32(253, 253, 150, 255); return new Color32(253, 253, 150, 255);
} }
} }
} }

30
Assets/Fungus/Flowchart/Scripts/Commands/Call.cs

@ -1,17 +1,16 @@
/** // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
using UnityEngine; using UnityEngine;
using UnityEngine.Serialization; using UnityEngine.Serialization;
using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
using System; using System;
namespace Fungus namespace Fungus
{ {
/// <summary>
/// Execute another block in the same Flowchart as the command, or in a different Flowchart.
/// </summary>
[CommandInfo("Flow", [CommandInfo("Flow",
"Call", "Call",
"Execute another block in the same Flowchart as the command, or in a different Flowchart.")] "Execute another block in the same Flowchart as the command, or in a different Flowchart.")]
@ -19,15 +18,15 @@ namespace Fungus
public class Call : Command public class Call : Command
{ {
[Tooltip("Flowchart which contains the block to execute. If none is specified then the current Flowchart is used.")] [Tooltip("Flowchart which contains the block to execute. If none is specified then the current Flowchart is used.")]
public Flowchart targetFlowchart; [SerializeField] protected Flowchart targetFlowchart;
[FormerlySerializedAs("targetSequence")] [FormerlySerializedAs("targetSequence")]
[Tooltip("Block to start executing")] [Tooltip("Block to start executing")]
public Block targetBlock; [SerializeField] protected Block targetBlock;
[Tooltip("Command index to start executing")] [Tooltip("Command index to start executing")]
[FormerlySerializedAs("commandIndex")] [FormerlySerializedAs("commandIndex")]
public int startIndex; [SerializeField] protected int startIndex;
public enum CallMode public enum CallMode
{ {
@ -37,7 +36,7 @@ namespace Fungus
} }
[Tooltip("Select if the calling block should stop or continue executing commands, or wait until the called block finishes.")] [Tooltip("Select if the calling block should stop or continue executing commands, or wait until the called block finishes.")]
public CallMode callMode; [SerializeField] protected CallMode callMode;
public override void OnEnter() public override void OnEnter()
{ {
@ -46,7 +45,7 @@ namespace Fungus
if (targetBlock != null) if (targetBlock != null)
{ {
// Check if calling your own parent block // Check if calling your own parent block
if (targetBlock == parentBlock) if (targetBlock == ParentBlock)
{ {
// Just ignore the callmode in this case, and jump to first command in list // Just ignore the callmode in this case, and jump to first command in list
Continue(0); Continue(0);
@ -58,7 +57,7 @@ namespace Fungus
if (callMode == CallMode.WaitUntilFinished) if (callMode == CallMode.WaitUntilFinished)
{ {
onComplete = delegate { onComplete = delegate {
flowchart.selectedBlock = parentBlock; flowchart.SelectedBlock = ParentBlock;
Continue(); Continue();
}; };
} }
@ -68,9 +67,9 @@ namespace Fungus
{ {
// If the executing block is currently selected then follow the execution // If the executing block is currently selected then follow the execution
// onto the next block in the inspector. // onto the next block in the inspector.
if (flowchart.selectedBlock == parentBlock) if (flowchart.SelectedBlock == ParentBlock)
{ {
flowchart.selectedBlock = targetBlock; flowchart.SelectedBlock = targetBlock;
} }
StartCoroutine(targetBlock.Execute(startIndex, onComplete)); StartCoroutine(targetBlock.Execute(startIndex, onComplete));
@ -110,7 +109,7 @@ namespace Fungus
} }
else else
{ {
summary = targetBlock.blockName; summary = targetBlock.BlockName;
} }
switch (callMode) switch (callMode)
@ -134,5 +133,4 @@ namespace Fungus
return new Color32(235, 191, 217, 255); return new Color32(235, 191, 217, 255);
} }
} }
} }

22
Assets/Fungus/Flowchart/Scripts/Commands/CallMethod.cs

@ -1,16 +1,15 @@
/** // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
using UnityEngine; using UnityEngine;
using System.Collections;
namespace Fungus namespace Fungus
{ {
// This command is called "Call Method" because a) it's more descriptive than Send Message and we're already have /// <summary>
// a Send Message command for sending messages to trigger block execution. /// Calls a named method on a GameObject using the GameObject.SendMessage() system.
/// This command is called "Call Method" because a) it's more descriptive than Send Message and we're already have
/// a Send Message command for sending messages to trigger block execution.
/// </summary>
[CommandInfo("Scripting", [CommandInfo("Scripting",
"Call Method", "Call Method",
"Calls a named method on a GameObject using the GameObject.SendMessage() system.")] "Calls a named method on a GameObject using the GameObject.SendMessage() system.")]
@ -18,13 +17,13 @@ namespace Fungus
public class CallMethod : Command public class CallMethod : Command
{ {
[Tooltip("Target monobehavior which contains the method we want to call")] [Tooltip("Target monobehavior which contains the method we want to call")]
public GameObject targetObject; [SerializeField] protected GameObject targetObject;
[Tooltip("Name of the method to call")] [Tooltip("Name of the method to call")]
public string methodName = ""; [SerializeField] protected string methodName = "";
[Tooltip("Delay (in seconds) before the method will be called")] [Tooltip("Delay (in seconds) before the method will be called")]
public float delay; [SerializeField] protected float delay;
public override void OnEnter() public override void OnEnter()
{ {
@ -72,5 +71,4 @@ namespace Fungus
return new Color32(235, 191, 217, 255); return new Color32(235, 191, 217, 255);
} }
} }
} }

16
Assets/Fungus/Flowchart/Scripts/Commands/Comment.cs

@ -1,14 +1,13 @@
/** // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
using UnityEngine; using UnityEngine;
using System.Collections;
using System.Collections.Generic;
namespace Fungus namespace Fungus
{ {
/// <summary>
/// Use comments to record design notes and reminders about your game.
/// </summary>
[CommandInfo("", [CommandInfo("",
"Comment", "Comment",
"Use comments to record design notes and reminders about your game.")] "Use comments to record design notes and reminders about your game.")]
@ -16,11 +15,11 @@ namespace Fungus
public class Comment : Command public class Comment : Command
{ {
[Tooltip("Name of Commenter")] [Tooltip("Name of Commenter")]
public string commenterName = ""; [SerializeField] protected string commenterName = "";
[Tooltip("Text to display for this comment")] [Tooltip("Text to display for this comment")]
[TextArea(2,4)] [TextArea(2,4)]
public string commentText = ""; [SerializeField] protected string commentText = "";
public override void OnEnter() public override void OnEnter()
{ {
@ -41,5 +40,4 @@ namespace Fungus
return new Color32(220, 220, 220, 255); return new Color32(220, 220, 220, 255);
} }
} }
} }

11
Assets/Fungus/Flowchart/Scripts/Commands/Condition.cs

@ -1,11 +1,7 @@
/** // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
using UnityEngine; using UnityEngine;
using System.Collections;
using System.Collections.Generic;
namespace Fungus namespace Fungus
{ {
@ -23,7 +19,7 @@ namespace Fungus
public abstract class Condition : Command public abstract class Condition : Command
{ {
[Tooltip("The type of comparison to be performed")] [Tooltip("The type of comparison to be performed")]
public CompareOperator compareOperator; [SerializeField] protected CompareOperator compareOperator;
public static string GetOperatorDescription(CompareOperator compareOperator) public static string GetOperatorDescription(CompareOperator compareOperator)
{ {
@ -53,5 +49,4 @@ namespace Fungus
return summary; return summary;
} }
} }
} }

15
Assets/Fungus/Flowchart/Scripts/Commands/DebugLog.cs

@ -1,13 +1,13 @@
/** // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
using UnityEngine; using UnityEngine;
using System.Collections;
namespace Fungus namespace Fungus
{ {
/// <summary>
/// Writes a log message to the debug console.
/// </summary>
[CommandInfo("Scripting", [CommandInfo("Scripting",
"Debug Log", "Debug Log",
"Writes a log message to the debug console.")] "Writes a log message to the debug console.")]
@ -22,10 +22,10 @@ namespace Fungus
} }
[Tooltip("Display type of debug log info")] [Tooltip("Display type of debug log info")]
public DebugLogType logType; [SerializeField] protected DebugLogType logType;
[Tooltip("Text to write to the debug log. Supports variable substitution, e.g. {$Myvar}")] [Tooltip("Text to write to the debug log. Supports variable substitution, e.g. {$Myvar}")]
public StringDataMulti logMessage; [SerializeField] protected StringDataMulti logMessage;
public override void OnEnter () public override void OnEnter ()
{ {
@ -58,5 +58,4 @@ namespace Fungus
return new Color32(235, 191, 217, 255); return new Color32(235, 191, 217, 255);
} }
} }
} }

16
Assets/Fungus/Flowchart/Scripts/Commands/DeleteSaveKey.cs

@ -1,14 +1,13 @@
/** // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
using UnityEngine; using UnityEngine;
using System;
using System.Collections;
namespace Fungus namespace Fungus
{ {
/// <summary>
/// Deletes a saved value from permanent storage.
/// </summary>
[CommandInfo("Variable", [CommandInfo("Variable",
"Delete Save Key", "Delete Save Key",
"Deletes a saved value from permanent storage.")] "Deletes a saved value from permanent storage.")]
@ -16,7 +15,7 @@ namespace Fungus
public class DeleteSaveKey : Command public class DeleteSaveKey : Command
{ {
[Tooltip("Name of the saved value. Supports variable substition e.g. \"player_{$PlayerNumber}")] [Tooltip("Name of the saved value. Supports variable substition e.g. \"player_{$PlayerNumber}")]
public string key = ""; [SerializeField] protected string key = "";
public override void OnEnter() public override void OnEnter()
{ {
@ -50,6 +49,5 @@ namespace Fungus
{ {
return new Color32(235, 191, 217, 255); return new Color32(235, 191, 217, 255);
} }
} }
} }

14
Assets/Fungus/Flowchart/Scripts/Commands/Destroy.cs

@ -1,15 +1,14 @@
/** // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
using UnityEngine; using UnityEngine;
using UnityEngine.Serialization; using UnityEngine.Serialization;
using System.Collections;
using System.Collections.Generic;
namespace Fungus namespace Fungus
{ {
/// <summary>
/// Destroys a specified game object in the scene.
/// </summary>
[CommandInfo("Scripting", [CommandInfo("Scripting",
"Destroy", "Destroy",
"Destroys a specified game object in the scene.")] "Destroys a specified game object in the scene.")]
@ -18,7 +17,7 @@ namespace Fungus
public class Destroy : Command public class Destroy : Command
{ {
[Tooltip("Reference to game object to destroy")] [Tooltip("Reference to game object to destroy")]
public GameObjectData _targetGameObject; [SerializeField] protected GameObjectData _targetGameObject;
public override void OnEnter() public override void OnEnter()
{ {
@ -60,5 +59,4 @@ namespace Fungus
#endregion #endregion
} }
} }

24
Assets/Fungus/Flowchart/Scripts/Commands/Else.cs

@ -1,14 +1,13 @@
/** // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
using UnityEngine; using UnityEngine;
using System.Collections;
using System.Collections.Generic;
namespace Fungus namespace Fungus
{ {
/// <summary>
/// Marks the start of a command block to be executed when the preceding If statement is False.
/// </summary>
[CommandInfo("Flow", [CommandInfo("Flow",
"Else", "Else",
"Marks the start of a command block to be executed when the preceding If statement is False.")] "Marks the start of a command block to be executed when the preceding If statement is False.")]
@ -17,13 +16,13 @@ namespace Fungus
{ {
public override void OnEnter() public override void OnEnter()
{ {
if (parentBlock == null) if (ParentBlock == null)
{ {
return; return;
} }
// Stop if this is the last command in the list // Stop if this is the last command in the list
if (commandIndex >= parentBlock.commandList.Count - 1) if (CommandIndex >= ParentBlock.CommandList.Count - 1)
{ {
StopParentBlock(); StopParentBlock();
return; return;
@ -31,17 +30,17 @@ namespace Fungus
// Find the next End command at the same indent level as this Else command // Find the next End command at the same indent level as this Else command
int indent = indentLevel; int indent = indentLevel;
for (int i = commandIndex + 1; i < parentBlock.commandList.Count; ++i) for (int i = CommandIndex + 1; i < ParentBlock.CommandList.Count; ++i)
{ {
Command command = parentBlock.commandList[i]; Command command = ParentBlock.CommandList[i];
if (command.indentLevel == indent) if (command.IndentLevel == indent)
{ {
System.Type type = command.GetType(); System.Type type = command.GetType();
if (type == typeof(End)) if (type == typeof(End))
{ {
// Execute command immediately after the EndIf command // Execute command immediately after the EndIf command
Continue(command.commandIndex + 1); Continue(command.CommandIndex + 1);
return; return;
} }
} }
@ -66,5 +65,4 @@ namespace Fungus
return new Color32(253, 253, 150, 255); return new Color32(253, 253, 150, 255);
} }
} }
} }

27
Assets/Fungus/Flowchart/Scripts/Commands/ElseIf.cs

@ -1,26 +1,22 @@
/** // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
using UnityEngine; using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;
namespace Fungus namespace Fungus
{ {
/// <summary>
/// Marks the start of a command block to be executed when the preceding If statement is False and the test expression is true.
/// </summary>
[CommandInfo("Flow", [CommandInfo("Flow",
"Else If", "Else If",
"Marks the start of a command block to be executed when the preceding If statement is False and the test expression is true.")] "Marks the start of a command block to be executed when the preceding If statement is False and the test expression is true.")]
[AddComponentMenu("")] [AddComponentMenu("")]
public class ElseIf : If public class ElseIf : If
{ {
public override void OnEnter() public override void OnEnter()
{ {
System.Type previousCommandType = parentBlock.GetPreviousActiveCommandType(); System.Type previousCommandType = ParentBlock.GetPreviousActiveCommandType();
if (previousCommandType == typeof(If) || if (previousCommandType == typeof(If) ||
previousCommandType == typeof(ElseIf) ) previousCommandType == typeof(ElseIf) )
@ -34,7 +30,7 @@ namespace Fungus
// but will also jump to a following Else command. // but will also jump to a following Else command.
// Stop if this is the last command in the list // Stop if this is the last command in the list
if (commandIndex >= parentBlock.commandList.Count - 1) if (CommandIndex >= ParentBlock.CommandList.Count - 1)
{ {
StopParentBlock(); StopParentBlock();
return; return;
@ -42,17 +38,17 @@ namespace Fungus
// Find the next End command at the same indent level as this Else If command // Find the next End command at the same indent level as this Else If command
int indent = indentLevel; int indent = indentLevel;
for (int i = commandIndex + 1; i < parentBlock.commandList.Count; ++i) for (int i = CommandIndex + 1; i < ParentBlock.CommandList.Count; ++i)
{ {
Command command = parentBlock.commandList[i]; Command command = ParentBlock.CommandList[i];
if (command.indentLevel == indent) if (command.IndentLevel == indent)
{ {
System.Type type = command.GetType(); System.Type type = command.GetType();
if (type == typeof(End)) if (type == typeof(End))
{ {
// Execute command immediately after the Else or End command // Execute command immediately after the Else or End command
Continue(command.commandIndex + 1); Continue(command.CommandIndex + 1);
return; return;
} }
} }
@ -78,5 +74,4 @@ namespace Fungus
return new Color32(253, 253, 150, 255); return new Color32(253, 253, 150, 255);
} }
} }
} }

22
Assets/Fungus/Flowchart/Scripts/Commands/End.cs

@ -1,31 +1,28 @@
/** // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
using UnityEngine; using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
namespace Fungus namespace Fungus
{ {
/// <summary>
/// Marks the end of a conditional block.
/// </summary>
[CommandInfo("Flow", [CommandInfo("Flow",
"End", "End",
"Marks the end of a conditional block.")] "Marks the end of a conditional block.")]
[AddComponentMenu("")] [AddComponentMenu("")]
public class End : Command public class End : Command
{ {
[NonSerialized] public bool Loop { get; set; }
public bool loop = false;
public override void OnEnter() public override void OnEnter()
{ {
if (loop) if (Loop)
{ {
for (int i = commandIndex - 1; i >= 0; --i) for (int i = CommandIndex - 1; i >= 0; --i)
{ {
System.Type commandType = parentBlock.commandList[i].GetType(); System.Type commandType = ParentBlock.CommandList[i].GetType();
if (commandType == typeof(While)) if (commandType == typeof(While))
{ {
Continue(i); Continue(i);
@ -47,5 +44,4 @@ namespace Fungus
return new Color32(253, 253, 150, 255); return new Color32(253, 253, 150, 255);
} }
} }
} }

39
Assets/Fungus/Flowchart/Scripts/Commands/If.cs

@ -1,15 +1,13 @@
/** // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
using UnityEngine; using UnityEngine;
using System.Collections;
using System.Collections.Generic;
namespace Fungus namespace Fungus
{ {
/// <summary>
/// If the test expression is true, execute the following command block.
/// </summary>
[CommandInfo("Flow", [CommandInfo("Flow",
"If", "If",
"If the test expression is true, execute the following command block.")] "If the test expression is true, execute the following command block.")]
@ -21,23 +19,23 @@ namespace Fungus
typeof(IntegerVariable), typeof(IntegerVariable),
typeof(FloatVariable), typeof(FloatVariable),
typeof(StringVariable))] typeof(StringVariable))]
public Variable variable; [SerializeField] protected Variable variable;
[Tooltip("Boolean value to compare against")] [Tooltip("Boolean value to compare against")]
public BooleanData booleanData; [SerializeField] protected BooleanData booleanData;
[Tooltip("Integer value to compare against")] [Tooltip("Integer value to compare against")]
public IntegerData integerData; [SerializeField] protected IntegerData integerData;
[Tooltip("Float value to compare against")] [Tooltip("Float value to compare against")]
public FloatData floatData; [SerializeField] protected FloatData floatData;
[Tooltip("String value to compare against")] [Tooltip("String value to compare against")]
public StringDataMulti stringData; [SerializeField] protected StringDataMulti stringData;
public override void OnEnter() public override void OnEnter()
{ {
if (parentBlock == null) if (ParentBlock == null)
{ {
return; return;
} }
@ -100,16 +98,16 @@ namespace Fungus
protected virtual void OnFalse() protected virtual void OnFalse()
{ {
// Last command in block // Last command in block
if (commandIndex >= parentBlock.commandList.Count) if (CommandIndex >= ParentBlock.CommandList.Count)
{ {
StopParentBlock(); StopParentBlock();
return; return;
} }
// Find the next Else, ElseIf or End command at the same indent level as this If command // Find the next Else, ElseIf or End command at the same indent level as this If command
for (int i = commandIndex + 1; i < parentBlock.commandList.Count; ++i) for (int i = CommandIndex + 1; i < ParentBlock.CommandList.Count; ++i)
{ {
Command nextCommand = parentBlock.commandList[i]; Command nextCommand = ParentBlock.CommandList[i];
if (nextCommand == null) if (nextCommand == null)
{ {
@ -121,7 +119,7 @@ namespace Fungus
if (!nextCommand.enabled || if (!nextCommand.enabled ||
nextCommand.GetType() == typeof(Comment) || nextCommand.GetType() == typeof(Comment) ||
nextCommand.GetType() == typeof(Label) || nextCommand.GetType() == typeof(Label) ||
nextCommand.indentLevel != indentLevel) nextCommand.IndentLevel != indentLevel)
{ {
continue; continue;
} }
@ -130,7 +128,7 @@ namespace Fungus
if (type == typeof(Else) || if (type == typeof(Else) ||
type == typeof(End)) type == typeof(End))
{ {
if (i >= parentBlock.commandList.Count - 1) if (i >= ParentBlock.CommandList.Count - 1)
{ {
// Last command in Block, so stop // Last command in Block, so stop
StopParentBlock(); StopParentBlock();
@ -138,7 +136,7 @@ namespace Fungus
else else
{ {
// Execute command immediately after the Else or End command // Execute command immediately after the Else or End command
Continue(nextCommand.commandIndex + 1); Continue(nextCommand.CommandIndex + 1);
return; return;
} }
} }
@ -162,7 +160,7 @@ namespace Fungus
return "Error: No variable selected"; return "Error: No variable selected";
} }
string summary = variable.key + " "; string summary = variable.Key + " ";
summary += Condition.GetOperatorDescription(compareOperator) + " "; summary += Condition.GetOperatorDescription(compareOperator) + " ";
if (variable.GetType() == typeof(BooleanVariable)) if (variable.GetType() == typeof(BooleanVariable))
@ -200,5 +198,4 @@ namespace Fungus
return new Color32(253, 253, 150, 255); return new Color32(253, 253, 150, 255);
} }
} }
} }

46
Assets/Fungus/Flowchart/Scripts/Commands/InvokeEvent.cs

@ -1,23 +1,22 @@
/** // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
using UnityEngine; using UnityEngine;
using System.Collections;
using System; using System;
using UnityEngine.Events; using UnityEngine.Events;
namespace Fungus namespace Fungus
{ {
/// <summary>
/// Calls a list of component methods via the Unity Event System (as used in the Unity UI)
/// This command is more efficient than the Invoke Method command but can only pass a single parameter and doesn't support return values.
/// This command uses the UnityEvent system to call methods in script. http://docs.unity3d.com/Manual/UnityEvents.html
/// </summary>
[CommandInfo("Scripting", [CommandInfo("Scripting",
"Invoke Event", "Invoke Event",
"Calls a list of component methods via the Unity Event System (as used in the Unity UI). " + "Calls a list of component methods via the Unity Event System (as used in the Unity UI). " +
"This command is more efficient than the Invoke Method command but can only pass a single parameter and doesn't support return values.")] "This command is more efficient than the Invoke Method command but can only pass a single parameter and doesn't support return values.")]
[AddComponentMenu("")] [AddComponentMenu("")]
// This command uses the UnityEvent system to call methods in script.
// http://docs.unity3d.com/Manual/UnityEvents.html
public class InvokeEvent : Command public class InvokeEvent : Command
{ {
[Serializable] public class BooleanEvent : UnityEvent<bool> {} [Serializable] public class BooleanEvent : UnityEvent<bool> {}
@ -35,36 +34,36 @@ namespace Fungus
} }
[Tooltip("Delay (in seconds) before the methods will be called")] [Tooltip("Delay (in seconds) before the methods will be called")]
public float delay; [SerializeField] protected float delay;
public InvokeType invokeType; [SerializeField] protected InvokeType invokeType;
[Tooltip("List of methods to call. Supports methods with no parameters or exactly one string, int, float or object parameter.")] [Tooltip("List of methods to call. Supports methods with no parameters or exactly one string, int, float or object parameter.")]
public UnityEvent staticEvent = new UnityEvent(); [SerializeField] protected UnityEvent staticEvent = new UnityEvent();
[Tooltip("Boolean parameter to pass to the invoked methods.")] [Tooltip("Boolean parameter to pass to the invoked methods.")]
public BooleanData booleanParameter; [SerializeField] protected BooleanData booleanParameter;
[Tooltip("List of methods to call. Supports methods with one boolean parameter.")] [Tooltip("List of methods to call. Supports methods with one boolean parameter.")]
public BooleanEvent booleanEvent = new BooleanEvent(); [SerializeField] protected BooleanEvent booleanEvent = new BooleanEvent();
[Tooltip("Integer parameter to pass to the invoked methods.")] [Tooltip("Integer parameter to pass to the invoked methods.")]
public IntegerData integerParameter; [SerializeField] protected IntegerData integerParameter;
[Tooltip("List of methods to call. Supports methods with one integer parameter.")] [Tooltip("List of methods to call. Supports methods with one integer parameter.")]
public IntegerEvent integerEvent = new IntegerEvent(); [SerializeField] protected IntegerEvent integerEvent = new IntegerEvent();
[Tooltip("Float parameter to pass to the invoked methods.")] [Tooltip("Float parameter to pass to the invoked methods.")]
public FloatData floatParameter; [SerializeField] protected FloatData floatParameter;
[Tooltip("List of methods to call. Supports methods with one float parameter.")] [Tooltip("List of methods to call. Supports methods with one float parameter.")]
public FloatEvent floatEvent = new FloatEvent(); [SerializeField] protected FloatEvent floatEvent = new FloatEvent();
[Tooltip("String parameter to pass to the invoked methods.")] [Tooltip("String parameter to pass to the invoked methods.")]
public StringDataMulti stringParameter; [SerializeField] protected StringDataMulti stringParameter;
[Tooltip("List of methods to call. Supports methods with one string parameter.")] [Tooltip("List of methods to call. Supports methods with one string parameter.")]
public StringEvent stringEvent = new StringEvent(); [SerializeField] protected StringEvent stringEvent = new StringEvent();
public override void OnEnter() public override void OnEnter()
{ {
@ -89,16 +88,16 @@ namespace Fungus
staticEvent.Invoke(); staticEvent.Invoke();
break; break;
case InvokeType.DynamicBoolean: case InvokeType.DynamicBoolean:
booleanEvent.Invoke(booleanParameter); booleanEvent.Invoke(booleanParameter.Value);
break; break;
case InvokeType.DynamicInteger: case InvokeType.DynamicInteger:
integerEvent.Invoke(integerParameter); integerEvent.Invoke(integerParameter.Value);
break; break;
case InvokeType.DynamicFloat: case InvokeType.DynamicFloat:
floatEvent.Invoke(floatParameter); floatEvent.Invoke(floatParameter.Value);
break; break;
case InvokeType.DynamicString: case InvokeType.DynamicString:
stringEvent.Invoke(stringParameter); stringEvent.Invoke(stringParameter.Value);
break; break;
} }
} }
@ -135,5 +134,4 @@ namespace Fungus
return new Color32(235, 191, 217, 255); return new Color32(235, 191, 217, 255);
} }
} }
} }

90
Assets/Fungus/Flowchart/Scripts/Commands/InvokeMethod.cs

@ -1,12 +1,9 @@
/** // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
using UnityEngine; using UnityEngine;
using System.Collections; using System.Collections;
using System.Reflection; using System.Reflection;
using System.Linq;
using System.Collections.Generic; using System.Collections.Generic;
using System; using System;
using UnityEngine.Events; using UnityEngine.Events;
@ -14,58 +11,62 @@ using MarkerMetro.Unity.WinLegacy.Reflection;
namespace Fungus namespace Fungus
{ {
/// <summary>
/// Invokes a method of a component via reflection. Supports passing multiple parameters and storing returned values in a Fungus variable.
/// </summary>
[CommandInfo("Scripting", [CommandInfo("Scripting",
"Invoke Method", "Invoke Method",
"Invokes a method of a component via reflection. Supports passing multiple parameters and storing returned values in a Fungus variable.")] "Invokes a method of a component via reflection. Supports passing multiple parameters and storing returned values in a Fungus variable.")]
public class InvokeMethod : Command public class InvokeMethod : Command
{ {
[Tooltip("GameObject containing the component method to be invoked")] [Tooltip("GameObject containing the component method to be invoked")]
public GameObject targetObject; [SerializeField] protected GameObject targetObject;
public GameObject TargetObject { get { return targetObject; } }
[HideInInspector] [HideInInspector]
[Tooltip("Name of assembly containing the target component")] [Tooltip("Name of assembly containing the target component")]
public string targetComponentAssemblyName; [SerializeField] protected string targetComponentAssemblyName;
[HideInInspector] [HideInInspector]
[Tooltip("Full name of the target component")] [Tooltip("Full name of the target component")]
public string targetComponentFullname; [SerializeField] protected string targetComponentFullname;
[HideInInspector] [HideInInspector]
[Tooltip("Display name of the target component")] [Tooltip("Display name of the target component")]
public string targetComponentText; [SerializeField] protected string targetComponentText;
[HideInInspector] [HideInInspector]
[Tooltip("Name of target method to invoke on the target component")] [Tooltip("Name of target method to invoke on the target component")]
public string targetMethod; [SerializeField] protected string targetMethod;
[HideInInspector] [HideInInspector]
[Tooltip("Display name of target method to invoke on the target component")] [Tooltip("Display name of target method to invoke on the target component")]
public string targetMethodText; [SerializeField] protected string targetMethodText;
[HideInInspector] [HideInInspector]
[Tooltip("List of parameters to pass to the invoked method")] [Tooltip("List of parameters to pass to the invoked method")]
public InvokeMethodParameter[] methodParameters; [SerializeField] protected InvokeMethodParameter[] methodParameters;
[HideInInspector] [HideInInspector]
[Tooltip("If true, store the return value in a flowchart variable of the same type.")] [Tooltip("If true, store the return value in a flowchart variable of the same type.")]
public bool saveReturnValue; [SerializeField] protected bool saveReturnValue;
[HideInInspector] [HideInInspector]
[Tooltip("Name of Fungus variable to store the return value in")] [Tooltip("Name of Fungus variable to store the return value in")]
public string returnValueVariableKey; [SerializeField] protected string returnValueVariableKey;
[HideInInspector] [HideInInspector]
[Tooltip("The type of the return value")] [Tooltip("The type of the return value")]
public string returnValueType; [SerializeField] protected string returnValueType;
[HideInInspector] [HideInInspector]
[Tooltip("If true, list all inherited methods for the component")] [Tooltip("If true, list all inherited methods for the component")]
public bool showInherited; [SerializeField] protected bool showInherited;
[HideInInspector] [HideInInspector]
[Tooltip("The coroutine call behavior for methods that return IEnumerator")] [Tooltip("The coroutine call behavior for methods that return IEnumerator")]
public Fungus.Call.CallMode callMode; [SerializeField] protected Call.CallMode callMode;
protected Type componentType; protected Type componentType;
protected Component objComponent; protected Component objComponent;
@ -198,62 +199,62 @@ namespace Fungus
case "System.Int32": case "System.Int32":
var intvalue = flowChart.GetVariable<IntegerVariable>(item.variableKey); var intvalue = flowChart.GetVariable<IntegerVariable>(item.variableKey);
if (intvalue != null) if (intvalue != null)
objValue = intvalue.value; objValue = intvalue.Value;
break; break;
case "System.Boolean": case "System.Boolean":
var boolean = flowChart.GetVariable<BooleanVariable>(item.variableKey); var boolean = flowChart.GetVariable<BooleanVariable>(item.variableKey);
if (boolean != null) if (boolean != null)
objValue = boolean.value; objValue = boolean.Value;
break; break;
case "System.Single": case "System.Single":
var floatvalue = flowChart.GetVariable<FloatVariable>(item.variableKey); var floatvalue = flowChart.GetVariable<FloatVariable>(item.variableKey);
if (floatvalue != null) if (floatvalue != null)
objValue = floatvalue.value; objValue = floatvalue.Value;
break; break;
case "System.String": case "System.String":
var stringvalue = flowChart.GetVariable<StringVariable>(item.variableKey); var stringvalue = flowChart.GetVariable<StringVariable>(item.variableKey);
if (stringvalue != null) if (stringvalue != null)
objValue = stringvalue.value; objValue = stringvalue.Value;
break; break;
case "UnityEngine.Color": case "UnityEngine.Color":
var color = flowChart.GetVariable<ColorVariable>(item.variableKey); var color = flowChart.GetVariable<ColorVariable>(item.variableKey);
if (color != null) if (color != null)
objValue = color.value; objValue = color.Value;
break; break;
case "UnityEngine.GameObject": case "UnityEngine.GameObject":
var gameObject = flowChart.GetVariable<GameObjectVariable>(item.variableKey); var gameObject = flowChart.GetVariable<GameObjectVariable>(item.variableKey);
if (gameObject != null) if (gameObject != null)
objValue = gameObject.value; objValue = gameObject.Value;
break; break;
case "UnityEngine.Material": case "UnityEngine.Material":
var material = flowChart.GetVariable<MaterialVariable>(item.variableKey); var material = flowChart.GetVariable<MaterialVariable>(item.variableKey);
if (material != null) if (material != null)
objValue = material.value; objValue = material.Value;
break; break;
case "UnityEngine.Sprite": case "UnityEngine.Sprite":
var sprite = flowChart.GetVariable<SpriteVariable>(item.variableKey); var sprite = flowChart.GetVariable<SpriteVariable>(item.variableKey);
if (sprite != null) if (sprite != null)
objValue = sprite.value; objValue = sprite.Value;
break; break;
case "UnityEngine.Texture": case "UnityEngine.Texture":
var texture = flowChart.GetVariable<TextureVariable>(item.variableKey); var texture = flowChart.GetVariable<TextureVariable>(item.variableKey);
if (texture != null) if (texture != null)
objValue = texture.value; objValue = texture.Value;
break; break;
case "UnityEngine.Vector2": case "UnityEngine.Vector2":
var vector2 = flowChart.GetVariable<Vector2Variable>(item.variableKey); var vector2 = flowChart.GetVariable<Vector2Variable>(item.variableKey);
if (vector2 != null) if (vector2 != null)
objValue = vector2.value; objValue = vector2.Value;
break; break;
case "UnityEngine.Vector3": case "UnityEngine.Vector3":
var vector3 = flowChart.GetVariable<Vector3Variable>(item.variableKey); var vector3 = flowChart.GetVariable<Vector3Variable>(item.variableKey);
if (vector3 != null) if (vector3 != null)
objValue = vector3.value; objValue = vector3.Value;
break; break;
default: default:
var obj = flowChart.GetVariable<ObjectVariable>(item.variableKey); var obj = flowChart.GetVariable<ObjectVariable>(item.variableKey);
if (obj != null) if (obj != null)
objValue = obj.value; objValue = obj.Value;
break; break;
} }
@ -271,40 +272,40 @@ namespace Fungus
switch (returnType) switch (returnType)
{ {
case "System.Int32": case "System.Int32":
flowChart.GetVariable<IntegerVariable>(key).value = (int)value; flowChart.GetVariable<IntegerVariable>(key).Value = (int)value;
break; break;
case "System.Boolean": case "System.Boolean":
flowChart.GetVariable<BooleanVariable>(key).value = (bool)value; flowChart.GetVariable<BooleanVariable>(key).Value = (bool)value;
break; break;
case "System.Single": case "System.Single":
flowChart.GetVariable<FloatVariable>(key).value = (float)value; flowChart.GetVariable<FloatVariable>(key).Value = (float)value;
break; break;
case "System.String": case "System.String":
flowChart.GetVariable<StringVariable>(key).value = (string)value; flowChart.GetVariable<StringVariable>(key).Value = (string)value;
break; break;
case "UnityEngine.Color": case "UnityEngine.Color":
flowChart.GetVariable<ColorVariable>(key).value = (UnityEngine.Color)value; flowChart.GetVariable<ColorVariable>(key).Value = (UnityEngine.Color)value;
break; break;
case "UnityEngine.GameObject": case "UnityEngine.GameObject":
flowChart.GetVariable<GameObjectVariable>(key).value = (UnityEngine.GameObject)value; flowChart.GetVariable<GameObjectVariable>(key).Value = (UnityEngine.GameObject)value;
break; break;
case "UnityEngine.Material": case "UnityEngine.Material":
flowChart.GetVariable<MaterialVariable>(key).value = (UnityEngine.Material)value; flowChart.GetVariable<MaterialVariable>(key).Value = (UnityEngine.Material)value;
break; break;
case "UnityEngine.Sprite": case "UnityEngine.Sprite":
flowChart.GetVariable<SpriteVariable>(key).value = (UnityEngine.Sprite)value; flowChart.GetVariable<SpriteVariable>(key).Value = (UnityEngine.Sprite)value;
break; break;
case "UnityEngine.Texture": case "UnityEngine.Texture":
flowChart.GetVariable<TextureVariable>(key).value = (UnityEngine.Texture)value; flowChart.GetVariable<TextureVariable>(key).Value = (UnityEngine.Texture)value;
break; break;
case "UnityEngine.Vector2": case "UnityEngine.Vector2":
flowChart.GetVariable<Vector2Variable>(key).value = (UnityEngine.Vector2)value; flowChart.GetVariable<Vector2Variable>(key).Value = (UnityEngine.Vector2)value;
break; break;
case "UnityEngine.Vector3": case "UnityEngine.Vector3":
flowChart.GetVariable<Vector3Variable>(key).value = (UnityEngine.Vector3)value; flowChart.GetVariable<Vector3Variable>(key).Value = (UnityEngine.Vector3)value;
break; break;
default: default:
flowChart.GetVariable<ObjectVariable>(key).value = (UnityEngine.Object)value; flowChart.GetVariable<ObjectVariable>(key).Value = (UnityEngine.Object)value;
break; break;
} }
} }
@ -398,5 +399,4 @@ namespace Fungus
return types[typeName]; return types[typeName];
} }
} }
} }

20
Assets/Fungus/Flowchart/Scripts/Commands/Jump.cs

@ -1,13 +1,14 @@
/** // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
using UnityEngine; using UnityEngine;
using UnityEngine.Serialization; using UnityEngine.Serialization;
namespace Fungus namespace Fungus
{ {
/// <summary>
/// Move execution to a specific Label command in the same block.
/// </summary>
[CommandInfo("Flow", [CommandInfo("Flow",
"Jump", "Jump",
"Move execution to a specific Label command in the same block")] "Move execution to a specific Label command in the same block")]
@ -16,7 +17,7 @@ namespace Fungus
public class Jump : Command public class Jump : Command
{ {
[Tooltip("Name of a label in this block to jump to")] [Tooltip("Name of a label in this block to jump to")]
public StringData _targetLabel = new StringData(""); [SerializeField] protected StringData _targetLabel = new StringData("");
public override void OnEnter() public override void OnEnter()
{ {
@ -26,13 +27,13 @@ namespace Fungus
return; return;
} }
foreach (Command command in parentBlock.commandList) foreach (Command command in ParentBlock.CommandList)
{ {
Label label = command as Label; Label label = command as Label;
if (label != null && if (label != null &&
label.key == _targetLabel.Value) label.Key == _targetLabel.Value)
{ {
Continue(label.commandIndex + 1); Continue(label.CommandIndex + 1);
return; return;
} }
} }
@ -65,12 +66,11 @@ namespace Fungus
{ {
if (targetLabelOLD != null) if (targetLabelOLD != null)
{ {
_targetLabel.Value = targetLabelOLD.key; _targetLabel.Value = targetLabelOLD.Key;
targetLabelOLD = null; targetLabelOLD = null;
} }
} }
#endregion #endregion
} }
} }

16
Assets/Fungus/Flowchart/Scripts/Commands/Label.cs

@ -1,14 +1,13 @@
/** // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
using UnityEngine; using UnityEngine;
using System.Collections;
using System.Collections.Generic;
namespace Fungus namespace Fungus
{ {
/// <summary>
/// Marks a position in the command list for execution to jump to.
/// </summary>
[CommandInfo("Flow", [CommandInfo("Flow",
"Label", "Label",
"Marks a position in the command list for execution to jump to.")] "Marks a position in the command list for execution to jump to.")]
@ -16,7 +15,9 @@ namespace Fungus
public class Label : Command public class Label : Command
{ {
[Tooltip("Display name for the label")] [Tooltip("Display name for the label")]
public string key = ""; [SerializeField] protected string key = "";
public string Key { get { return key; } }
public override void OnEnter() public override void OnEnter()
{ {
@ -33,5 +34,4 @@ namespace Fungus
return new Color32(200, 200, 253, 255); return new Color32(200, 200, 253, 255);
} }
} }
} }

31
Assets/Fungus/Flowchart/Scripts/Commands/LoadScene.cs

@ -1,30 +1,32 @@
/** // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
using UnityEngine; using UnityEngine;
using UnityEngine.Serialization; using UnityEngine.Serialization;
using System;
using System.Collections;
namespace Fungus namespace Fungus
{ {
/// <summary>
/// Loads a new Unity scene and displays an optional loading image. This is useful
/// for splitting a large game across multiple scene files to reduce peak memory
/// usage. Previously loaded assets will be released before loading the scene to free up memory.
/// The scene to be loaded must be added to the scene list in Build Settings.")]
/// </summary>
[CommandInfo("Flow", [CommandInfo("Flow",
"Load Scene", "Load Scene",
"Loads a new Unity scene and displays an optional loading image. This is useful " + "Loads a new Unity scene and displays an optional loading image. This is useful " +
"for splitting a large game across multiple scene files to reduce peak memory " + "for splitting a large game across multiple scene files to reduce peak memory " +
"usage. Previously loaded assets will be released before loading the scene to free up memory." + "usage. Previously loaded assets will be released before loading the scene to free up memory." +
"The scene to be loaded must be added to the scene list in Build Settings.")] "The scene to be loaded must be added to the scene list in Build Settings.")]
[AddComponentMenu("")] [AddComponentMenu("")]
[ExecuteInEditMode] [ExecuteInEditMode]
public class LoadScene : Command public class LoadScene : Command
{ {
[Tooltip("Name of the scene to load. The scene must also be added to the build settings.")] [Tooltip("Name of the scene to load. The scene must also be added to the build settings.")]
public StringData _sceneName = new StringData(""); [SerializeField] protected StringData _sceneName = new StringData("");
[Tooltip("Image to display while loading the scene")] [Tooltip("Image to display while loading the scene")]
public Texture2D loadingImage; [SerializeField] protected Texture2D loadingImage;
public override void OnEnter() public override void OnEnter()
{ {
@ -38,7 +40,7 @@ namespace Fungus
return "Error: No scene name selected"; return "Error: No scene name selected";
} }
return _sceneName; return _sceneName.Value;
} }
public override Color GetButtonColor() public override Color GetButtonColor()
@ -61,5 +63,4 @@ namespace Fungus
#endregion #endregion
} }
} }

26
Assets/Fungus/Flowchart/Scripts/Commands/LoadVariable.cs

@ -1,14 +1,13 @@
/** // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
using UnityEngine; using UnityEngine;
using System;
using System.Collections;
namespace Fungus namespace Fungus
{ {
/// <summary>
/// Loads a saved value and stores it in a Boolean, Integer, Float or String variable. If the key is not found then the variable is not modified.
/// </summary>
[CommandInfo("Variable", [CommandInfo("Variable",
"Load Variable", "Load Variable",
"Loads a saved value and stores it in a Boolean, Integer, Float or String variable. If the key is not found then the variable is not modified.")] "Loads a saved value and stores it in a Boolean, Integer, Float or String variable. If the key is not found then the variable is not modified.")]
@ -16,7 +15,7 @@ namespace Fungus
public class LoadVariable : Command public class LoadVariable : Command
{ {
[Tooltip("Name of the saved value. Supports variable substition e.g. \"player_{$PlayerNumber}\"")] [Tooltip("Name of the saved value. Supports variable substition e.g. \"player_{$PlayerNumber}\"")]
public string key = ""; [SerializeField] protected string key = "";
[Tooltip("Variable to store the value in.")] [Tooltip("Variable to store the value in.")]
[VariableProperty(typeof(BooleanVariable), [VariableProperty(typeof(BooleanVariable),
@ -47,7 +46,7 @@ namespace Fungus
if (booleanVariable != null) if (booleanVariable != null)
{ {
// PlayerPrefs does not have bool accessors, so just use int // PlayerPrefs does not have bool accessors, so just use int
booleanVariable.value = (PlayerPrefs.GetInt(prefsKey) == 1); booleanVariable.Value = (PlayerPrefs.GetInt(prefsKey) == 1);
} }
} }
else if (variableType == typeof(IntegerVariable)) else if (variableType == typeof(IntegerVariable))
@ -55,7 +54,7 @@ namespace Fungus
IntegerVariable integerVariable = variable as IntegerVariable; IntegerVariable integerVariable = variable as IntegerVariable;
if (integerVariable != null) if (integerVariable != null)
{ {
integerVariable.value = PlayerPrefs.GetInt(prefsKey); integerVariable.Value = PlayerPrefs.GetInt(prefsKey);
} }
} }
else if (variableType == typeof(FloatVariable)) else if (variableType == typeof(FloatVariable))
@ -63,7 +62,7 @@ namespace Fungus
FloatVariable floatVariable = variable as FloatVariable; FloatVariable floatVariable = variable as FloatVariable;
if (floatVariable != null) if (floatVariable != null)
{ {
floatVariable.value = PlayerPrefs.GetFloat(prefsKey); floatVariable.Value = PlayerPrefs.GetFloat(prefsKey);
} }
} }
else if (variableType == typeof(StringVariable)) else if (variableType == typeof(StringVariable))
@ -71,7 +70,7 @@ namespace Fungus
StringVariable stringVariable = variable as StringVariable; StringVariable stringVariable = variable as StringVariable;
if (stringVariable != null) if (stringVariable != null)
{ {
stringVariable.value = PlayerPrefs.GetString(prefsKey); stringVariable.Value = PlayerPrefs.GetString(prefsKey);
} }
} }
@ -90,13 +89,12 @@ namespace Fungus
return "Error: No variable selected"; return "Error: No variable selected";
} }
return "'" + key + "' into " + variable.key; return "'" + key + "' into " + variable.Key;
} }
public override Color GetButtonColor() public override Color GetButtonColor()
{ {
return new Color32(235, 191, 217, 255); return new Color32(235, 191, 217, 255);
} }
} }
} }

14
Assets/Fungus/Flowchart/Scripts/Commands/OpenURL.cs

@ -1,22 +1,21 @@
/** // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
using UnityEngine; using UnityEngine;
using System.Collections;
using Fungus; using Fungus;
namespace Fungus namespace Fungus
{ {
/// <summary>
/// Opens the specified URL in the browser.
/// </summary>
[CommandInfo("Scripting", [CommandInfo("Scripting",
"Open URL", "Open URL",
"Opens the specified URL in the browser.")] "Opens the specified URL in the browser.")]
public class LinkToWebsite : Command public class LinkToWebsite : Command
{ {
[Tooltip("URL to open in the browser")] [Tooltip("URL to open in the browser")]
public StringData url = new StringData(); [SerializeField] protected StringData url = new StringData();
public override void OnEnter() public override void OnEnter()
{ {
@ -35,5 +34,4 @@ namespace Fungus
return new Color32(235, 191, 217, 255); return new Color32(235, 191, 217, 255);
} }
} }
} }

12
Assets/Fungus/Flowchart/Scripts/Commands/Quit.cs

@ -1,14 +1,13 @@
/** // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
using UnityEngine; using UnityEngine;
using System;
using System.Collections;
namespace Fungus namespace Fungus
{ {
/// <summary>
/// Quits the application. Does not work in Editor or Webplayer builds. Shouldn't generally be used on iOS.
/// </summary>
[CommandInfo("Flow", [CommandInfo("Flow",
"Quit", "Quit",
"Quits the application. Does not work in Editor or Webplayer builds. Shouldn't generally be used on iOS.")] "Quits the application. Does not work in Editor or Webplayer builds. Shouldn't generally be used on iOS.")]
@ -28,5 +27,4 @@ namespace Fungus
return new Color32(235, 191, 217, 255); return new Color32(235, 191, 217, 255);
} }
} }
} }

21
Assets/Fungus/Flowchart/Scripts/Commands/RandomFloat.cs

@ -1,13 +1,13 @@
/** // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
using UnityEngine; using UnityEngine;
using System.Collections;
namespace Fungus namespace Fungus
{ {
/// <summary>
/// Sets an float variable to a random value in the defined range.
/// </summary>
[CommandInfo("Variable", [CommandInfo("Variable",
"Random Float", "Random Float",
"Sets an float variable to a random value in the defined range.")] "Sets an float variable to a random value in the defined range.")]
@ -16,19 +16,19 @@ namespace Fungus
{ {
[Tooltip("The variable whos value will be set")] [Tooltip("The variable whos value will be set")]
[VariableProperty(typeof(FloatVariable))] [VariableProperty(typeof(FloatVariable))]
public FloatVariable variable; [SerializeField] protected FloatVariable variable;
[Tooltip("Minimum value for random range")] [Tooltip("Minimum value for random range")]
public FloatData minValue; [SerializeField] protected FloatData minValue;
[Tooltip("Maximum value for random range")] [Tooltip("Maximum value for random range")]
public FloatData maxValue; [SerializeField] protected FloatData maxValue;
public override void OnEnter() public override void OnEnter()
{ {
if (variable != null) if (variable != null)
{ {
variable.value = Random.Range(minValue.Value, maxValue.Value); variable.Value = Random.Range(minValue.Value, maxValue.Value);
} }
Continue(); Continue();
@ -41,7 +41,7 @@ namespace Fungus
return "Error: Variable not selected"; return "Error: Variable not selected";
} }
return variable.key; return variable.Key;
} }
public override bool HasReference(Variable variable) public override bool HasReference(Variable variable)
@ -54,5 +54,4 @@ namespace Fungus
return new Color32(253, 253, 150, 255); return new Color32(253, 253, 150, 255);
} }
} }
} }

21
Assets/Fungus/Flowchart/Scripts/Commands/RandomInteger.cs

@ -1,13 +1,13 @@
/** // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
using UnityEngine; using UnityEngine;
using System.Collections;
namespace Fungus namespace Fungus
{ {
/// <summary>
/// Sets an integer variable to a random value in the defined range.
/// </summary>
[CommandInfo("Variable", [CommandInfo("Variable",
"Random Integer", "Random Integer",
"Sets an integer variable to a random value in the defined range.")] "Sets an integer variable to a random value in the defined range.")]
@ -16,19 +16,19 @@ namespace Fungus
{ {
[Tooltip("The variable whos value will be set")] [Tooltip("The variable whos value will be set")]
[VariableProperty(typeof(IntegerVariable))] [VariableProperty(typeof(IntegerVariable))]
public IntegerVariable variable; [SerializeField] protected IntegerVariable variable;
[Tooltip("Minimum value for random range")] [Tooltip("Minimum value for random range")]
public IntegerData minValue; [SerializeField] protected IntegerData minValue;
[Tooltip("Maximum value for random range")] [Tooltip("Maximum value for random range")]
public IntegerData maxValue; [SerializeField] protected IntegerData maxValue;
public override void OnEnter() public override void OnEnter()
{ {
if (variable != null) if (variable != null)
{ {
variable.value = Random.Range(minValue.Value, maxValue.Value); variable.Value = Random.Range(minValue.Value, maxValue.Value);
} }
Continue(); Continue();
@ -41,7 +41,7 @@ namespace Fungus
return "Error: Variable not selected"; return "Error: Variable not selected";
} }
return variable.key; return variable.Key;
} }
public override bool HasReference(Variable variable) public override bool HasReference(Variable variable)
@ -54,5 +54,4 @@ namespace Fungus
return new Color32(253, 253, 150, 255); return new Color32(253, 253, 150, 255);
} }
} }
} }

20
Assets/Fungus/Flowchart/Scripts/Commands/ReadTextFile.cs

@ -1,26 +1,25 @@
/** // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
using UnityEngine; using UnityEngine;
using System.Collections;
using Fungus; using Fungus;
namespace Fungus namespace Fungus
{ {
/// <summary>
/// Reads in a text file and stores the contents in a string variable.
/// </summary>
[CommandInfo("Variable", [CommandInfo("Variable",
"Read Text File", "Read Text File",
"Reads in a text file and stores the contents in a string variable")] "Reads in a text file and stores the contents in a string variable")]
public class ReadTextFile : Command public class ReadTextFile : Command
{ {
[Tooltip("Text file to read into the string variable")] [Tooltip("Text file to read into the string variable")]
public TextAsset textFile; [SerializeField] protected TextAsset textFile;
[Tooltip("String variable to store the tex file contents in")] [Tooltip("String variable to store the tex file contents in")]
[VariableProperty(typeof(StringVariable))] [VariableProperty(typeof(StringVariable))]
public StringVariable stringVariable; [SerializeField] protected StringVariable stringVariable;
public override void OnEnter() public override void OnEnter()
{ {
@ -31,7 +30,7 @@ namespace Fungus
return; return;
} }
stringVariable.value = textFile.text; stringVariable.Value = textFile.text;
Continue(); Continue();
} }
@ -48,7 +47,7 @@ namespace Fungus
return "Error: Text file not selected"; return "Error: Text file not selected";
} }
return stringVariable.key; return stringVariable.Key;
} }
public override bool HasReference(Variable variable) public override bool HasReference(Variable variable)
@ -61,5 +60,4 @@ namespace Fungus
return new Color32(253, 253, 150, 255); return new Color32(253, 253, 150, 255);
} }
} }
} }

16
Assets/Fungus/Flowchart/Scripts/Commands/Reset.cs

@ -1,14 +1,13 @@
/** // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
using UnityEngine; using UnityEngine;
using System.Collections;
using System.Collections.Generic;
namespace Fungus namespace Fungus
{ {
/// <summary>
/// Resets the state of all commands and variables in the Flowchart.
/// </summary>
[CommandInfo("Variable", [CommandInfo("Variable",
"Reset", "Reset",
"Resets the state of all commands and variables in the Flowchart.")] "Resets the state of all commands and variables in the Flowchart.")]
@ -16,10 +15,10 @@ namespace Fungus
public class Reset : Command public class Reset : Command
{ {
[Tooltip("Reset state of all commands in the script")] [Tooltip("Reset state of all commands in the script")]
public bool resetCommands = true; [SerializeField] protected bool resetCommands = true;
[Tooltip("Reset variables back to their default values")] [Tooltip("Reset variables back to their default values")]
public bool resetVariables = true; [SerializeField] protected bool resetVariables = true;
public override void OnEnter() public override void OnEnter()
{ {
@ -32,5 +31,4 @@ namespace Fungus
return new Color32(235, 191, 217, 255); return new Color32(235, 191, 217, 255);
} }
} }
} }

28
Assets/Fungus/Flowchart/Scripts/Commands/SaveVariable.cs

@ -1,14 +1,15 @@
/** // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
using UnityEngine; using UnityEngine;
using System;
using System.Collections;
namespace Fungus namespace Fungus
{ {
/// <summary>
/// Save an Boolean, Integer, Float or String variable to persistent storage using a string key.
/// The value can be loaded again later using the Load Variable command. You can also
/// use the Set Save Profile command to manage separate save profiles for multiple players.
/// </summary>
[CommandInfo("Variable", [CommandInfo("Variable",
"Save Variable", "Save Variable",
"Save an Boolean, Integer, Float or String variable to persistent storage using a string key. " + "Save an Boolean, Integer, Float or String variable to persistent storage using a string key. " +
@ -18,7 +19,7 @@ namespace Fungus
public class SaveVariable : Command public class SaveVariable : Command
{ {
[Tooltip("Name of the saved value. Supports variable substition e.g. \"player_{$PlayerNumber}")] [Tooltip("Name of the saved value. Supports variable substition e.g. \"player_{$PlayerNumber}")]
public string key = ""; [SerializeField] protected string key = "";
[Tooltip("Variable to read the value from. Only Boolean, Integer, Float and String are supported.")] [Tooltip("Variable to read the value from. Only Boolean, Integer, Float and String are supported.")]
[VariableProperty(typeof(BooleanVariable), [VariableProperty(typeof(BooleanVariable),
@ -49,7 +50,7 @@ namespace Fungus
if (booleanVariable != null) if (booleanVariable != null)
{ {
// PlayerPrefs does not have bool accessors, so just use int // PlayerPrefs does not have bool accessors, so just use int
PlayerPrefs.SetInt(prefsKey, booleanVariable.value ? 1 : 0); PlayerPrefs.SetInt(prefsKey, booleanVariable.Value ? 1 : 0);
} }
} }
else if (variableType == typeof(IntegerVariable)) else if (variableType == typeof(IntegerVariable))
@ -57,7 +58,7 @@ namespace Fungus
IntegerVariable integerVariable = variable as IntegerVariable; IntegerVariable integerVariable = variable as IntegerVariable;
if (integerVariable != null) if (integerVariable != null)
{ {
PlayerPrefs.SetInt(prefsKey, integerVariable.value); PlayerPrefs.SetInt(prefsKey, integerVariable.Value);
} }
} }
else if (variableType == typeof(FloatVariable)) else if (variableType == typeof(FloatVariable))
@ -65,7 +66,7 @@ namespace Fungus
FloatVariable floatVariable = variable as FloatVariable; FloatVariable floatVariable = variable as FloatVariable;
if (floatVariable != null) if (floatVariable != null)
{ {
PlayerPrefs.SetFloat(prefsKey, floatVariable.value); PlayerPrefs.SetFloat(prefsKey, floatVariable.Value);
} }
} }
else if (variableType == typeof(StringVariable)) else if (variableType == typeof(StringVariable))
@ -73,7 +74,7 @@ namespace Fungus
StringVariable stringVariable = variable as StringVariable; StringVariable stringVariable = variable as StringVariable;
if (stringVariable != null) if (stringVariable != null)
{ {
PlayerPrefs.SetString(prefsKey, stringVariable.value); PlayerPrefs.SetString(prefsKey, stringVariable.Value);
} }
} }
@ -92,13 +93,12 @@ namespace Fungus
return "Error: No variable selected"; return "Error: No variable selected";
} }
return variable.key + " into '" + key + "'"; return variable.Key + " into '" + key + "'";
} }
public override Color GetButtonColor() public override Color GetButtonColor()
{ {
return new Color32(235, 191, 217, 255); return new Color32(235, 191, 217, 255);
} }
} }
} }

15
Assets/Fungus/Flowchart/Scripts/Commands/SendMessage.cs

@ -1,14 +1,14 @@
/** // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
using UnityEngine; using UnityEngine;
using UnityEngine.Serialization; using UnityEngine.Serialization;
using System.Collections;
namespace Fungus namespace Fungus
{ {
/// <summary>
/// Sends a message to either the owner Flowchart or all Flowcharts in the scene. Blocks can listen for this message using a Message Received event handler.
/// </summary>
[CommandInfo("Flow", [CommandInfo("Flow",
"Send Message", "Send Message",
"Sends a message to either the owner Flowchart or all Flowcharts in the scene. Blocks can listen for this message using a Message Received event handler.")] "Sends a message to either the owner Flowchart or all Flowcharts in the scene. Blocks can listen for this message using a Message Received event handler.")]
@ -23,10 +23,10 @@ namespace Fungus
} }
[Tooltip("Target flowchart(s) to send the message to")] [Tooltip("Target flowchart(s) to send the message to")]
public MessageTarget messageTarget; [SerializeField] protected MessageTarget messageTarget;
[Tooltip("Name of the message to send")] [Tooltip("Name of the message to send")]
public StringData _message = new StringData(""); [SerializeField] protected StringData _message = new StringData("");
public override void OnEnter() public override void OnEnter()
{ {
@ -89,5 +89,4 @@ namespace Fungus
#endregion #endregion
} }
} }

16
Assets/Fungus/Flowchart/Scripts/Commands/SetActive.cs

@ -1,15 +1,14 @@
/** // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
using UnityEngine; using UnityEngine;
using UnityEngine.Serialization; using UnityEngine.Serialization;
using System.Collections;
using System.Collections.Generic;
namespace Fungus namespace Fungus
{ {
/// <summary>
/// Sets a game object in the scene to be active / inactive.
/// </summary>
[CommandInfo("Scripting", [CommandInfo("Scripting",
"Set Active", "Set Active",
"Sets a game object in the scene to be active / inactive.")] "Sets a game object in the scene to be active / inactive.")]
@ -18,10 +17,10 @@ namespace Fungus
public class SetActive : Command public class SetActive : Command
{ {
[Tooltip("Reference to game object to enable / disable")] [Tooltip("Reference to game object to enable / disable")]
public GameObjectData _targetGameObject; [SerializeField] protected GameObjectData _targetGameObject;
[Tooltip("Set to true to enable the game object")] [Tooltip("Set to true to enable the game object")]
public BooleanData activeState; [SerializeField] protected BooleanData activeState;
public override void OnEnter() public override void OnEnter()
{ {
@ -63,5 +62,4 @@ namespace Fungus
#endregion #endregion
} }
} }

20
Assets/Fungus/Flowchart/Scripts/Commands/SetSaveProfile.cs

@ -1,7 +1,5 @@
/** // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
using UnityEngine; using UnityEngine;
using System; using System;
@ -9,19 +7,22 @@ using System.Collections;
namespace Fungus namespace Fungus
{ {
/// <summary>
/// Sets the active profile that the Save Variable and Load Variable commands will use. This is useful to crete multiple player save games. Once set, the profile applies across all Flowcharts and will also persist across scene loads.
/// </summary>
[CommandInfo("Variable", [CommandInfo("Variable",
"Set Save Profile", "Set Save Profile",
"Sets the active profile that the Save Variable and Load Variable commands will use. This is useful to crete multiple player save games. Once set, the profile applies across all Flowcharts and will also persist across scene loads.")] "Sets the active profile that the Save Variable and Load Variable commands will use. This is useful to crete multiple player save games. Once set, the profile applies across all Flowcharts and will also persist across scene loads.")]
[AddComponentMenu("")] [AddComponentMenu("")]
public class SetSaveProfile : Command public class SetSaveProfile : Command
{ {
/** /// <summary>
* Shared save profile name used by SaveVariable and LoadVariable. /// Shared save profile name used by SaveVariable and LoadVariable.
*/ /// </summary>
public static string saveProfile = ""; public static string saveProfile = "";
[Tooltip("Name of save profile to make active.")] [Tooltip("Name of save profile to make active.")]
public string saveProfileName = ""; [SerializeField] protected string saveProfileName = "";
public override void OnEnter() public override void OnEnter()
{ {
@ -39,6 +40,5 @@ namespace Fungus
{ {
return new Color32(235, 191, 217, 255); return new Color32(235, 191, 217, 255);
} }
} }
} }

52
Assets/Fungus/Flowchart/Scripts/Commands/SetVariable.cs

@ -1,13 +1,13 @@
/** // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
using UnityEngine; using UnityEngine;
using System.Collections;
namespace Fungus namespace Fungus
{ {
/// <summary>
/// Sets a Boolean, Integer, Float or String variable to a new value using a simple arithmetic operation. The value can be a constant or reference another variable of the same type.
/// </summary>
[CommandInfo("Variable", [CommandInfo("Variable",
"Set Variable", "Set Variable",
"Sets a Boolean, Integer, Float or String variable to a new value using a simple arithmetic operation. The value can be a constant or reference another variable of the same type.")] "Sets a Boolean, Integer, Float or String variable to a new value using a simple arithmetic operation. The value can be a constant or reference another variable of the same type.")]
@ -29,22 +29,23 @@ namespace Fungus
typeof(IntegerVariable), typeof(IntegerVariable),
typeof(FloatVariable), typeof(FloatVariable),
typeof(StringVariable))] typeof(StringVariable))]
public Variable variable; [SerializeField] protected Variable variable;
[Tooltip("The type of math operation to be performed")] [Tooltip("The type of math operation to be performed")]
public SetOperator setOperator; [SerializeField] protected SetOperator setOperator;
public SetOperator _SetOperator { get { return setOperator; } }
[Tooltip("Boolean value to set with")] [Tooltip("Boolean value to set with")]
public BooleanData booleanData; [SerializeField] protected BooleanData booleanData;
[Tooltip("Integer value to set with")] [Tooltip("Integer value to set with")]
public IntegerData integerData; [SerializeField] protected IntegerData integerData;
[Tooltip("Float value to set with")] [Tooltip("Float value to set with")]
public FloatData floatData; [SerializeField] protected FloatData floatData;
[Tooltip("String value to set with")] [Tooltip("String value to set with")]
public StringDataMulti stringData; [SerializeField] protected StringDataMulti stringData;
public override void OnEnter() public override void OnEnter()
{ {
@ -60,7 +61,7 @@ namespace Fungus
return "Error: Variable not selected"; return "Error: Variable not selected";
} }
string description = variable.key; string description = variable.Key;
switch (setOperator) switch (setOperator)
{ {
@ -131,10 +132,10 @@ namespace Fungus
{ {
default: default:
case SetOperator.Assign: case SetOperator.Assign:
lhs.value = rhs; lhs.Value = rhs;
break; break;
case SetOperator.Negate: case SetOperator.Negate:
lhs.value = !rhs; lhs.Value = !rhs;
break; break;
} }
} }
@ -147,19 +148,19 @@ namespace Fungus
{ {
default: default:
case SetOperator.Assign: case SetOperator.Assign:
lhs.value = rhs; lhs.Value = rhs;
break; break;
case SetOperator.Add: case SetOperator.Add:
lhs.value += rhs; lhs.Value += rhs;
break; break;
case SetOperator.Subtract: case SetOperator.Subtract:
lhs.value -= rhs; lhs.Value -= rhs;
break; break;
case SetOperator.Multiply: case SetOperator.Multiply:
lhs.value *= rhs; lhs.Value *= rhs;
break; break;
case SetOperator.Divide: case SetOperator.Divide:
lhs.value /= rhs; lhs.Value /= rhs;
break; break;
} }
} }
@ -172,19 +173,19 @@ namespace Fungus
{ {
default: default:
case SetOperator.Assign: case SetOperator.Assign:
lhs.value = rhs; lhs.Value = rhs;
break; break;
case SetOperator.Add: case SetOperator.Add:
lhs.value += rhs; lhs.Value += rhs;
break; break;
case SetOperator.Subtract: case SetOperator.Subtract:
lhs.value -= rhs; lhs.Value -= rhs;
break; break;
case SetOperator.Multiply: case SetOperator.Multiply:
lhs.value *= rhs; lhs.Value *= rhs;
break; break;
case SetOperator.Divide: case SetOperator.Divide:
lhs.value /= rhs; lhs.Value /= rhs;
break; break;
} }
} }
@ -197,11 +198,10 @@ namespace Fungus
{ {
default: default:
case SetOperator.Assign: case SetOperator.Assign:
lhs.value = rhs; lhs.Value = rhs;
break; break;
} }
} }
} }
} }
} }

22
Assets/Fungus/Flowchart/Scripts/Commands/SpawnObject.cs

@ -1,17 +1,14 @@
/** // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
using UnityEngine; using UnityEngine;
using UnityEngine.Serialization; using UnityEngine.Serialization;
using System.Collections;
namespace Fungus namespace Fungus
{ {
// This command is called "Call Method" because a) it's more descriptive than Send Message and we're already have /// <summary>
// a Send Message command for sending messages to trigger block execution. /// Spawns a new object based on a reference to a scene or prefab game object.
/// </summary>
[CommandInfo("Scripting", [CommandInfo("Scripting",
"Spawn Object", "Spawn Object",
"Spawns a new object based on a reference to a scene or prefab game object.")] "Spawns a new object based on a reference to a scene or prefab game object.")]
@ -20,16 +17,16 @@ namespace Fungus
public class SpawnObject : Command public class SpawnObject : Command
{ {
[Tooltip("Game object to copy when spawning. Can be a scene object or a prefab.")] [Tooltip("Game object to copy when spawning. Can be a scene object or a prefab.")]
public GameObjectData _sourceObject; [SerializeField] protected GameObjectData _sourceObject;
[Tooltip("Transform to use for position of newly spawned object.")] [Tooltip("Transform to use for position of newly spawned object.")]
public TransformData _parentTransform; [SerializeField] protected TransformData _parentTransform;
[Tooltip("Local position of newly spawned object.")] [Tooltip("Local position of newly spawned object.")]
public Vector3Data _spawnPosition; [SerializeField] protected Vector3Data _spawnPosition;
[Tooltip("Local rotation of newly spawned object.")] [Tooltip("Local rotation of newly spawned object.")]
public Vector3Data _spawnRotation; [SerializeField] protected Vector3Data _spawnRotation;
public override void OnEnter() public override void OnEnter()
{ {
@ -99,5 +96,4 @@ namespace Fungus
#endregion #endregion
} }
} }

12
Assets/Fungus/Flowchart/Scripts/Commands/Stop.cs

@ -1,14 +1,13 @@
/** // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
using UnityEngine; using UnityEngine;
using System.Collections;
using System.Collections.Generic;
namespace Fungus namespace Fungus
{ {
/// <summary>
/// Stop executing the Block that contains this command.
/// </summary>
[CommandInfo("Flow", [CommandInfo("Flow",
"Stop", "Stop",
"Stop executing the Block that contains this command.")] "Stop executing the Block that contains this command.")]
@ -25,5 +24,4 @@ namespace Fungus
return new Color32(235, 191, 217, 255); return new Color32(235, 191, 217, 255);
} }
} }
} }

16
Assets/Fungus/Flowchart/Scripts/Commands/StopBlock.cs

@ -1,24 +1,23 @@
/** // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
using UnityEngine; using UnityEngine;
using System.Collections;
namespace Fungus namespace Fungus
{ {
/// <summary>
/// Stops executing the named Block.
/// </summary>
[CommandInfo("Flow", [CommandInfo("Flow",
"Stop Block", "Stop Block",
"Stops executing the named Block")] "Stops executing the named Block")]
public class StopBlock : Command public class StopBlock : Command
{ {
[Tooltip("Flowchart containing the Block. If none is specified, the parent Flowchart is used.")] [Tooltip("Flowchart containing the Block. If none is specified, the parent Flowchart is used.")]
public Flowchart flowchart; [SerializeField] protected Flowchart flowchart;
[Tooltip("Name of the Block to stop")] [Tooltip("Name of the Block to stop")]
public StringData blockName = new StringData(""); [SerializeField] protected StringData blockName = new StringData("");
public override void OnEnter() public override void OnEnter()
{ {
@ -54,5 +53,4 @@ namespace Fungus
return new Color32(253, 253, 150, 255); return new Color32(253, 253, 150, 255);
} }
} }
} }

15
Assets/Fungus/Flowchart/Scripts/Commands/StopFlowchart.cs

@ -1,14 +1,14 @@
/** // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
using UnityEngine; using UnityEngine;
using System.Collections;
using System.Collections.Generic; using System.Collections.Generic;
namespace Fungus namespace Fungus
{ {
/// <summary>
/// Stops execution of all Blocks in a Flowchart.
/// </summary>
[CommandInfo("Flow", [CommandInfo("Flow",
"Stop Flowchart", "Stop Flowchart",
"Stops execution of all Blocks in a Flowchart")] "Stops execution of all Blocks in a Flowchart")]
@ -16,10 +16,10 @@ namespace Fungus
public class StopFlowchart : Command public class StopFlowchart : Command
{ {
[Tooltip("Stop all executing Blocks in the Flowchart that contains this command")] [Tooltip("Stop all executing Blocks in the Flowchart that contains this command")]
public bool stopParentFlowchart; [SerializeField] protected bool stopParentFlowchart;
[Tooltip("Stop all executing Blocks in a list of target Flowcharts")] [Tooltip("Stop all executing Blocks in a list of target Flowcharts")]
public List<Flowchart> targetFlowcharts = new List<Flowchart>(); [SerializeField] protected List<Flowchart> targetFlowcharts = new List<Flowchart>();
public override void OnEnter() public override void OnEnter()
{ {
@ -57,5 +57,4 @@ namespace Fungus
return new Color32(235, 191, 217, 255); return new Color32(235, 191, 217, 255);
} }
} }
} }

14
Assets/Fungus/Flowchart/Scripts/Commands/Wait.cs

@ -1,15 +1,14 @@
/** // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
using UnityEngine; using UnityEngine;
using UnityEngine.Serialization; using UnityEngine.Serialization;
using System;
using System.Collections;
namespace Fungus namespace Fungus
{ {
/// <summary>
/// Waits for period of time before executing the next command in the block.
/// </summary>
[CommandInfo("Flow", [CommandInfo("Flow",
"Wait", "Wait",
"Waits for period of time before executing the next command in the block.")] "Waits for period of time before executing the next command in the block.")]
@ -18,7 +17,7 @@ namespace Fungus
public class Wait : Command public class Wait : Command
{ {
[Tooltip("Duration to wait for")] [Tooltip("Duration to wait for")]
public FloatData _duration = new FloatData(1); [SerializeField] protected FloatData _duration = new FloatData(1);
public override void OnEnter() public override void OnEnter()
{ {
@ -55,5 +54,4 @@ namespace Fungus
#endregion #endregion
} }
} }

25
Assets/Fungus/Flowchart/Scripts/Commands/While.cs

@ -1,15 +1,13 @@
/** // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
using UnityEngine; using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
namespace Fungus namespace Fungus
{ {
/// <summary>
/// Continuously loop through a block of commands while the condition is true. Use the Break command to force the loop to terminate immediately.
/// </summary>
[CommandInfo("Flow", [CommandInfo("Flow",
"While", "While",
"Continuously loop through a block of commands while the condition is true. Use the Break command to force the loop to terminate immediately.")] "Continuously loop through a block of commands while the condition is true. Use the Break command to force the loop to terminate immediately.")]
@ -26,12 +24,12 @@ namespace Fungus
// Find next End statement at same indent level // Find next End statement at same indent level
End endCommand = null; End endCommand = null;
for (int i = commandIndex + 1; i < parentBlock.commandList.Count; ++i) for (int i = CommandIndex + 1; i < ParentBlock.CommandList.Count; ++i)
{ {
End command = parentBlock.commandList[i] as End; End command = ParentBlock.CommandList[i] as End;
if (command != null && if (command != null &&
command.indentLevel == indentLevel) command.IndentLevel == indentLevel)
{ {
endCommand = command; endCommand = command;
break; break;
@ -41,13 +39,13 @@ namespace Fungus
if (execute) if (execute)
{ {
// Tell the following end command to loop back // Tell the following end command to loop back
endCommand.loop = true; endCommand.Loop = true;
Continue(); Continue();
} }
else else
{ {
// Continue at next command after End // Continue at next command after End
Continue (endCommand.commandIndex + 1); Continue (endCommand.CommandIndex + 1);
} }
} }
@ -60,6 +58,5 @@ namespace Fungus
{ {
return new Color32(253, 253, 150, 255); return new Color32(253, 253, 150, 255);
} }
} }
} }

53
Assets/Fungus/Flowchart/Scripts/EventHandler.cs

@ -1,17 +1,15 @@
/** // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
using UnityEngine; using UnityEngine;
using UnityEngine.Serialization; using UnityEngine.Serialization;
using System; using System;
using System.Collections;
using System.Collections.Generic;
namespace Fungus namespace Fungus
{ {
/// <summary>
/// Attribute class for Fungus event handlers.
/// </summary>
public class EventHandlerInfoAttribute : Attribute public class EventHandlerInfoAttribute : Attribute
{ {
public EventHandlerInfoAttribute(string category, string eventHandlerName, string helpText) public EventHandlerInfoAttribute(string category, string eventHandlerName, string helpText)
@ -26,26 +24,31 @@ namespace Fungus
public string HelpText { get; set; } public string HelpText { get; set; }
} }
/** /// <summary>
* A Block may have an associated Event Handler which starts executing commands when /// A Block may have an associated Event Handler which starts executing commands when
* a specific event occurs. /// a specific event occurs.
* To create a custom Event Handler, simply subclass EventHandler and call the ExecuteBlock() method /// To create a custom Event Handler, simply subclass EventHandler and call the ExecuteBlock() method
* when the event occurs. /// when the event occurs.
* Add an EventHandlerInfo attibute and your new EventHandler class will automatically appear in the /// Add an EventHandlerInfo attibute and your new EventHandler class will automatically appear in the
* 'Execute On Event' dropdown menu when a block is selected. /// 'Execute On Event' dropdown menu when a block is selected.
*/ /// </summary>
[RequireComponent(typeof(Block))] [RequireComponent(typeof(Block))]
[RequireComponent(typeof(Flowchart))] [RequireComponent(typeof(Flowchart))]
[AddComponentMenu("")] [AddComponentMenu("")]
public class EventHandler : MonoBehaviour public class EventHandler : MonoBehaviour
{ {
/// <summary>
/// Returns the parent Block which owns this Event Handler.
/// </summary>
/// <value>The parent block.</value>
[HideInInspector] [HideInInspector]
[FormerlySerializedAs("parentSequence")] [FormerlySerializedAs("parentSequence")]
public Block parentBlock; [SerializeField] protected Block parentBlock;
public Block ParentBlock { get { return parentBlock; } set { parentBlock = value; } }
/** /// <summary>
* The Event Handler should call this method when the event is detected. /// The Event Handler should call this method when the event is detected.
*/ /// </summary>
public virtual bool ExecuteBlock() public virtual bool ExecuteBlock()
{ {
if (parentBlock == null) if (parentBlock == null)
@ -53,7 +56,7 @@ namespace Fungus
return false; return false;
} }
if (parentBlock.eventHandler != this) if (parentBlock._EventHandler != this)
{ {
return false; return false;
} }
@ -61,17 +64,17 @@ namespace Fungus
Flowchart flowchart = parentBlock.GetFlowchart(); Flowchart flowchart = parentBlock.GetFlowchart();
// Auto-follow the executing block if none is currently selected // Auto-follow the executing block if none is currently selected
if (flowchart.selectedBlock == null) if (flowchart.SelectedBlock == null)
{ {
flowchart.selectedBlock = parentBlock; flowchart.SelectedBlock = parentBlock;
} }
return flowchart.ExecuteBlock(parentBlock); return flowchart.ExecuteBlock(parentBlock);
} }
/** /// <summary>
* Returns a custom summary for the event handler. /// Returns custom summary text for the event handler.
*/ /// </summary>
public virtual string GetSummary() public virtual string GetSummary()
{ {
return ""; return "";

12
Assets/Fungus/Flowchart/Scripts/EventHandlers/FlowchartEnabled.cs

@ -1,15 +1,13 @@
/** // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
using UnityEngine; using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
namespace Fungus namespace Fungus
{ {
/// <summary>
/// The block will execute when the Flowchart game object is enabled.
/// </summary>
[EventHandlerInfo("", [EventHandlerInfo("",
"Flowchart Enabled", "Flowchart Enabled",
"The block will execute when the Flowchart game object is enabled.")] "The block will execute when the Flowchart game object is enabled.")]

12
Assets/Fungus/Flowchart/Scripts/EventHandlers/GameStarted.cs

@ -1,15 +1,13 @@
/** // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
using UnityEngine; using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
namespace Fungus namespace Fungus
{ {
/// <summary>
/// The block will execute when the game starts playing.
/// </summary>
[EventHandlerInfo("", [EventHandlerInfo("",
"Game Started", "Game Started",
"The block will execute when the game starts playing.")] "The block will execute when the game starts playing.")]

14
Assets/Fungus/Flowchart/Scripts/EventHandlers/KeyPressed.cs

@ -1,13 +1,13 @@
/** // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
using UnityEngine; using UnityEngine;
using System.Collections;
namespace Fungus namespace Fungus
{ {
/// <summary>
/// The block will execute when a key press event occurs.
/// </summary>
[EventHandlerInfo("Input", [EventHandlerInfo("Input",
"Key Pressed", "Key Pressed",
"The block will execute when a key press event occurs.")] "The block will execute when a key press event occurs.")]
@ -22,10 +22,10 @@ namespace Fungus
} }
[Tooltip("The type of keypress to activate on")] [Tooltip("The type of keypress to activate on")]
public KeyPressType keyPressType; [SerializeField] protected KeyPressType keyPressType;
[Tooltip("Keycode of the key to activate on")] [Tooltip("Keycode of the key to activate on")]
public KeyCode keyCode; [SerializeField] protected KeyCode keyCode;
protected virtual void Update() protected virtual void Update()
{ {

13
Assets/Fungus/Flowchart/Scripts/EventHandlers/MessageReceived.cs

@ -1,13 +1,13 @@
/** // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
using UnityEngine; using UnityEngine;
using System.Collections;
namespace Fungus namespace Fungus
{ {
/// <summary>
/// The block will execute when the specified message is received from a Send Message command.
/// </summary>
[EventHandlerInfo("", [EventHandlerInfo("",
"Message Received", "Message Received",
"The block will execute when the specified message is received from a Send Message command.")] "The block will execute when the specified message is received from a Send Message command.")]
@ -15,7 +15,7 @@ namespace Fungus
public class MessageReceived : EventHandler public class MessageReceived : EventHandler
{ {
[Tooltip("Fungus message to listen for")] [Tooltip("Fungus message to listen for")]
public string message = ""; [SerializeField] protected string message = "";
public void OnSendFungusMessage(string message) public void OnSendFungusMessage(string message)
{ {
@ -30,5 +30,4 @@ namespace Fungus
return message; return message;
} }
} }
} }

565
Assets/Fungus/Flowchart/Scripts/Flowchart.cs

@ -1,7 +1,5 @@
/** // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
using UnityEngine; using UnityEngine;
using UnityEngine.EventSystems; using UnityEngine.EventSystems;
@ -14,185 +12,207 @@ using System.Text.RegularExpressions;
namespace Fungus namespace Fungus
{ {
/** /// <summary>
* Interface for Flowchart components which can be updated when the /// Interface for Flowchart components which can be updated when the
* scene loads in the editor. This is used to maintain backwards /// scene loads in the editor. This is used to maintain backwards
* compatibility with earlier versions of Fungus. /// compatibility with earlier versions of Fungus.
*/ /// </summary>
interface IUpdateable interface IUpdateable
{ {
void UpdateToVersion(int oldVersion, int newVersion); void UpdateToVersion(int oldVersion, int newVersion);
} }
/** /// <summary>
* Visual scripting controller for the Flowchart programming language. /// Visual scripting controller for the Flowchart programming language.
* Flowchart objects may be edited visually using the Flowchart editor window. /// Flowchart objects may be edited visually using the Flowchart editor window.
*/ /// </summary>
[ExecuteInEditMode] [ExecuteInEditMode]
public class Flowchart : MonoBehaviour, StringSubstituter.ISubstitutionHandler public class Flowchart : MonoBehaviour, StringSubstituter.ISubstitutionHandler
{ {
/** /// <summary>
* The current version of the Flowchart. Used for updating components. /// The current version of the Flowchart. Used for updating components.
*/ /// </summary>
public const int CURRENT_VERSION = 1; public const int CURRENT_VERSION = 1;
/** /// <summary>
* The name of the initial block in a new flowchart. /// The name of the initial block in a new flowchart.
*/ /// </summary>
public const string DEFAULT_BLOCK_NAME = "New Block"; public const string DEFAULT_BLOCK_NAME = "New Block";
/** /// <summary>
* Variable to track flowchart's version so components can update to new versions. /// Variable to track flowchart's version so components can update to new versions.
*/ /// </summary>
[HideInInspector] [HideInInspector]
public int version = 0; // Default to 0 to always trigger an update for older versions of Fungus. [SerializeField] protected int version = 0; // Default to 0 to always trigger an update for older versions of Fungus.
public int Version { set { version = value; } }
/** /// <summary>
* Scroll position of Flowchart editor window. /// Scroll position of Flowchart editor window.
*/ /// </summary>
[HideInInspector] [HideInInspector]
public Vector2 scrollPos; [SerializeField] protected Vector2 scrollPos;
public Vector2 ScrollPos { get { return scrollPos; } set { scrollPos = value; } }
/** /// <summary>
* Scroll position of Flowchart variables window. /// Scroll position of Flowchart variables window.
*/ /// </summary>
[HideInInspector] [HideInInspector]
public Vector2 variablesScrollPos; [SerializeField] protected Vector2 variablesScrollPos;
public Vector2 VariablesScrollPos { get { return variablesScrollPos; } set { variablesScrollPos = value; } }
/** /// <summary>
* Show the variables pane. /// Show the variables pane.
*/ /// </summary>
[HideInInspector] [HideInInspector]
public bool variablesExpanded = true; [SerializeField] protected bool variablesExpanded = true;
public bool VariablesExpanded { get { return variablesExpanded; } set { variablesExpanded = value; } }
/** /// <summary>
* Height of command block view in inspector. /// Height of command block view in inspector.
*/ /// </summary>
[HideInInspector] [HideInInspector]
public float blockViewHeight = 400; [SerializeField] protected float blockViewHeight = 400;
public float BlockViewHeight { get { return blockViewHeight; } set { blockViewHeight = value; } }
/** /// <summary>
* Zoom level of Flowchart editor window /// Zoom level of Flowchart editor window.
*/ /// </summary>
[HideInInspector] [HideInInspector]
public float zoom = 1f; [SerializeField] protected float zoom = 1f;
public float Zoom { get { return zoom; } set { zoom = value; } }
/** /// <summary>
* Scrollable area for Flowchart editor window. /// Scrollable area for Flowchart editor window.
*/ /// </summary>
[HideInInspector] [HideInInspector]
public Rect scrollViewRect; [SerializeField] protected Rect scrollViewRect;
public Rect ScrollViewRect { get { return scrollViewRect; } set { scrollViewRect = value; } }
/** /// <summary>
* Currently selected block in the Flowchart editor. /// Currently selected block in the Flowchart editor.
*/ /// </summary>
[HideInInspector] [HideInInspector]
[FormerlySerializedAs("selectedSequence")] [FormerlySerializedAs("selectedSequence")]
public Block selectedBlock; [SerializeField] protected Block selectedBlock;
public Block SelectedBlock { get { return selectedBlock; } set { selectedBlock = value; } }
/**
* Currently selected command in the Flowchart editor. /// <summary>
*/ /// Currently selected command in the Flowchart editor.
/// </summary>
[HideInInspector] [HideInInspector]
public List<Command> selectedCommands = new List<Command>(); [SerializeField] protected List<Command> selectedCommands = new List<Command>();
public List<Command> SelectedCommands { get { return selectedCommands; } }
/** /// <summary>
* The list of variables that can be accessed by the Flowchart. /// The list of variables that can be accessed by the Flowchart.
*/ /// </summary>
[HideInInspector] [HideInInspector]
public List<Variable> variables = new List<Variable>(); [SerializeField] protected List<Variable> variables = new List<Variable>();
public List<Variable> Variables { get { return variables; } }
/// <summary>
/// Description text displayed in the Flowchart editor window
/// </summary>
[TextArea(3, 5)] [TextArea(3, 5)]
[Tooltip("Description text displayed in the Flowchart editor window")] [Tooltip("Description text displayed in the Flowchart editor window")]
public string description = ""; [SerializeField] protected string description = "";
public string Description { get { return description; } }
/** /// <summary>
* Slow down execution in the editor to make it easier to visualise program flow. /// Slow down execution in the editor to make it easier to visualise program flow.
*/ /// </summary>
[Range(0f, 5f)] [Range(0f, 5f)]
[Tooltip("Adds a pause after each execution step to make it easier to visualise program flow. Editor only, has no effect in platform builds.")] [Tooltip("Adds a pause after each execution step to make it easier to visualise program flow. Editor only, has no effect in platform builds.")]
public float stepPause = 0f; [SerializeField] protected float stepPause = 0f;
public float StepPause { get { return stepPause; } }
/** /// <summary>
* Use command color when displaying the command list in the inspector. /// Use command color when displaying the command list in the inspector.
*/ /// </summary>
[Tooltip("Use command color when displaying the command list in the Fungus Editor window")] [Tooltip("Use command color when displaying the command list in the Fungus Editor window")]
public bool colorCommands = true; [SerializeField] protected bool colorCommands = true;
public bool ColorCommands { get { return colorCommands; } }
/** /// <summary>
* Hides the Flowchart block and command components in the inspector. /// Hides the Flowchart block and command components in the inspector.
* Deselect to inspect the block and command components that make up the Flowchart. /// Deselect to inspect the block and command components that make up the Flowchart.
*/ /// </summary>
[Tooltip("Hides the Flowchart block and command components in the inspector")] [Tooltip("Hides the Flowchart block and command components in the inspector. Deselect to inspect the block and command components that make up the Flowchart.")]
public bool hideComponents = true; [SerializeField] protected bool hideComponents = true;
/** /// <summary>
* Saves the selected block and commands when saving the scene. /// Saves the selected block and commands when saving the scene. Helps avoid version control conflicts if you've only changed the active selection.
* Helps avoid version control conflicts if you've only changed the active selection. /// </summary>
*/ [Tooltip("Saves the selected block and commands when saving the scene. Helps avoid version control conflicts if you've only changed the active selection.")]
[Tooltip("Saves the selected block and commands when saving the scene.")] [SerializeField] protected bool saveSelection = true;
public bool saveSelection = true; public bool SaveSelection { get { return saveSelection; } }
/** /// <summary>
* Unique identifier for identifying this flowchart in localized string keys. /// Unique identifier for identifying this flowchart in localized string keys.
*/ /// </summary>
[Tooltip("Unique identifier for this flowchart in localized string keys. If no id is specified then the name of the Flowchart object will be used.")] [Tooltip("Unique identifier for this flowchart in localized string keys. If no id is specified then the name of the Flowchart object will be used.")]
public string localizationId = ""; [SerializeField] protected string localizationId = "";
public string LocalizationId { get { return localizationId; } }
/** /// <summary>
* Display line numbers in the command list in the Block inspector. /// Display line numbers in the command list in the Block inspector.
*/ /// </summary>
[Tooltip("Display line numbers in the command list in the Block inspector.")] [Tooltip("Display line numbers in the command list in the Block inspector.")]
public bool showLineNumbers = false; [SerializeField] protected bool showLineNumbers = false;
public bool ShowLineNumbers { get { return showLineNumbers; } }
/** /// <summary>
* List of commands to hide in the Add Command menu. Use this to restrict the set of commands available when editing a Flowchart. /// List of commands to hide in the Add Command menu. Use this to restrict the set of commands available when editing a Flowchart.
*/ /// </summary>
[Tooltip("List of commands to hide in the Add Command menu. Use this to restrict the set of commands available when editing a Flowchart.")] [Tooltip("List of commands to hide in the Add Command menu. Use this to restrict the set of commands available when editing a Flowchart.")]
public List<string> hideCommands = new List<string>(); [SerializeField] protected List<string> hideCommands = new List<string>();
/// <summary>
/// Lua Environment to be used by default for all Execute Lua commands in this Flowchart.
/// </summary>
[Tooltip("Lua Environment to be used by default for all Execute Lua commands in this Flowchart")] [Tooltip("Lua Environment to be used by default for all Execute Lua commands in this Flowchart")]
public LuaEnvironment luaEnvironment; [SerializeField] protected LuaEnvironment luaEnvironment;
public LuaEnvironment _LuaEnvironment { get { return luaEnvironment; } }
/** /// <summary>
* The ExecuteLua command adds a global Lua variable with this name bound to the flowchart prior to executing. /// The ExecuteLua command adds a global Lua variable with this name bound to the flowchart prior to executing.
*/ /// </summary>
[Tooltip("The ExecuteLua command adds a global Lua variable with this name bound to the flowchart prior to executing.")] [Tooltip("The ExecuteLua command adds a global Lua variable with this name bound to the flowchart prior to executing.")]
public string luaBindingName = "flowchart"; [SerializeField] protected string luaBindingName = "flowchart";
public string LuaBindingName { get { return luaBindingName; } }
/** /// <summary>
* Position in the center of all blocks in the flowchart. /// Position in the center of all blocks in the flowchart.
*/ /// </summary>
[NonSerialized] public Vector2 CenterPosition { set; get; }
public Vector2 centerPosition = Vector2.zero;
/** /// <summary>
* Cached list of flowchart objects in the scene for fast lookup /// Cached list of flowchart objects in the scene for fast lookup.
*/ /// </summary>
public static List<Flowchart> cachedFlowcharts = new List<Flowchart>(); public static List<Flowchart> cachedFlowcharts = new List<Flowchart>();
protected static bool eventSystemPresent; protected static bool eventSystemPresent;
protected StringSubstituter stringSubstituer; protected StringSubstituter stringSubstituer;
/** /// <summary>
* Returns the next id to assign to a new flowchart item. /// Returns the next id to assign to a new flowchart item.
* Item ids increase monotically so they are guaranteed to /// Item ids increase monotically so they are guaranteed to
* be unique within a Flowchart. /// be unique within a Flowchart.
*/ /// </summary>
public int NextItemId() public int NextItemId()
{ {
int maxId = -1; int maxId = -1;
Block[] blocks = GetComponents<Block>(); Block[] blocks = GetComponents<Block>();
foreach (Block block in blocks) foreach (Block block in blocks)
{ {
maxId = Math.Max(maxId, block.itemId); maxId = Math.Max(maxId, block.ItemId);
} }
Command[] commands = GetComponents<Command>(); Command[] commands = GetComponents<Command>();
foreach (Command command in commands) foreach (Command command in commands)
{ {
maxId = Math.Max(maxId, command.itemId); maxId = Math.Max(maxId, command.ItemId);
} }
return maxId + 1; return maxId + 1;
} }
@ -292,23 +312,23 @@ namespace Fungus
Block[] blocks = GetComponents<Block>(); Block[] blocks = GetComponents<Block>();
foreach (Block block in blocks) foreach (Block block in blocks)
{ {
if (block.itemId == -1 || if (block.ItemId == -1 ||
usedIds.Contains(block.itemId)) usedIds.Contains(block.ItemId))
{ {
block.itemId = NextItemId(); block.ItemId = NextItemId();
} }
usedIds.Add(block.itemId); usedIds.Add(block.ItemId);
} }
Command[] commands = GetComponents<Command>(); Command[] commands = GetComponents<Command>();
foreach (Command command in commands) foreach (Command command in commands)
{ {
if (command.itemId == -1 || if (command.ItemId == -1 ||
usedIds.Contains(command.itemId)) usedIds.Contains(command.ItemId))
{ {
command.itemId = NextItemId(); command.ItemId = NextItemId();
} }
usedIds.Add(command.itemId); usedIds.Add(command.ItemId);
} }
} }
@ -337,7 +357,7 @@ namespace Fungus
bool found = false; bool found = false;
foreach (Block block in blocks) foreach (Block block in blocks)
{ {
if (block.commandList.Contains(command)) if (block.CommandList.Contains(command))
{ {
found = true; found = true;
break; break;
@ -355,7 +375,7 @@ namespace Fungus
bool found = false; bool found = false;
foreach (Block block in blocks) foreach (Block block in blocks)
{ {
if (block.eventHandler == eventHandler) if (block._EventHandler == eventHandler)
{ {
found = true; found = true;
break; break;
@ -375,29 +395,28 @@ namespace Fungus
return block; return block;
} }
/** /// <summary>
* Create a new block node which you can then add commands to. /// Create a new block node which you can then add commands to.
*/ /// </summary>
public virtual Block CreateBlock(Vector2 position) public virtual Block CreateBlock(Vector2 position)
{ {
Block b = CreateBlockComponent(gameObject); Block b = CreateBlockComponent(gameObject);
b.nodeRect.x = position.x; b._NodeRect = new Rect(position.x, position.y, 0, 0);
b.nodeRect.y = position.y; b.BlockName = GetUniqueBlockKey(b.BlockName, b);
b.blockName = GetUniqueBlockKey(b.blockName, b); b.ItemId = NextItemId();
b.itemId = NextItemId();
return b; return b;
} }
/** /// <summary>
* Returns the named Block in the flowchart, or null if not found. /// Returns the named Block in the flowchart, or null if not found.
*/ /// </summary>
public virtual Block FindBlock(string blockName) public virtual Block FindBlock(string blockName)
{ {
Block [] blocks = GetComponents<Block>(); Block [] blocks = GetComponents<Block>();
foreach (Block block in blocks) foreach (Block block in blocks)
{ {
if (block.blockName == blockName) if (block.BlockName == blockName)
{ {
return block; return block;
} }
@ -406,17 +425,15 @@ namespace Fungus
return null; return null;
} }
/** /// <summary>
* Execute a child block in the Flowchart. /// Execute a child block in the Flowchart.
* You can use this method in a UI event. e.g. to handle a button click. /// You can use this method in a UI event. e.g. to handle a button click.
* Returns true if the Block started execution.
*/
public virtual void ExecuteBlock(string blockName) public virtual void ExecuteBlock(string blockName)
{ {
Block block = null; Block block = null;
foreach (Block b in GetComponents<Block>()) foreach (Block b in GetComponents<Block>())
{ {
if (b.blockName == blockName) if (b.BlockName == blockName)
{ {
block = b; block = b;
break; break;
@ -435,12 +452,12 @@ namespace Fungus
} }
} }
/** /// <summary>
* Execute a child block in the flowchart. /// Execute a child block in the flowchart.
* The block must be in an idle state to be executed. /// The block must be in an idle state to be executed.
* This version provides extra options to control how the block is executed. /// This version provides extra options to control how the block is executed.
* Returns true if the Block started execution. /// Returns true if the Block started execution.
*/ /// </summary>
public virtual bool ExecuteBlock(Block block, int commandIndex = 0, Action onComplete = null) public virtual bool ExecuteBlock(Block block, int commandIndex = 0, Action onComplete = null)
{ {
if (block == null) if (block == null)
@ -467,9 +484,9 @@ namespace Fungus
return true; return true;
} }
/** /// <summary>
* Stop all executing Blocks in this Flowchart. /// Stop all executing Blocks in this Flowchart.
*/ /// </summary>
public virtual void StopAllBlocks() public virtual void StopAllBlocks()
{ {
Block [] blocks = GetComponents<Block>(); Block [] blocks = GetComponents<Block>();
@ -482,10 +499,10 @@ namespace Fungus
} }
} }
/** /// <summary>
* Sends a message to this Flowchart only. /// Sends a message to this Flowchart only.
* Any block with a matching MessageReceived event handler will start executing. /// Any block with a matching MessageReceived event handler will start executing.
*/ /// </summary>
public virtual void SendFungusMessage(string messageName) public virtual void SendFungusMessage(string messageName)
{ {
MessageReceived[] eventHandlers = GetComponents<MessageReceived>(); MessageReceived[] eventHandlers = GetComponents<MessageReceived>();
@ -495,10 +512,10 @@ namespace Fungus
} }
} }
/** /// <summary>
* Sends a message to all Flowchart objects in the current scene. /// Sends a message to all Flowchart objects in the current scene.
* Any block with a matching MessageReceived event handler will start executing. /// Any block with a matching MessageReceived event handler will start executing.
*/ /// </summary>
public static void BroadcastFungusMessage(string messageName) public static void BroadcastFungusMessage(string messageName)
{ {
MessageReceived[] eventHandlers = UnityEngine.Object.FindObjectsOfType<MessageReceived>(); MessageReceived[] eventHandlers = UnityEngine.Object.FindObjectsOfType<MessageReceived>();
@ -508,9 +525,9 @@ namespace Fungus
} }
} }
/** /// <summary>
* Returns a new variable key that is guaranteed not to clash with any existing variable in the list. /// Returns a new variable key that is guaranteed not to clash with any existing variable in the list.
*/ /// </summary>
public virtual string GetUniqueVariableKey(string originalKey, Variable ignoreVariable = null) public virtual string GetUniqueVariableKey(string originalKey, Variable ignoreVariable = null)
{ {
int suffix = 0; int suffix = 0;
@ -537,12 +554,12 @@ namespace Fungus
{ {
if (variable == null || if (variable == null ||
variable == ignoreVariable || variable == ignoreVariable ||
variable.key == null) variable.Key == null)
{ {
continue; continue;
} }
if (variable.key.Equals(key, StringComparison.CurrentCultureIgnoreCase)) if (variable.Key.Equals(key, StringComparison.CurrentCultureIgnoreCase))
{ {
collision = true; collision = true;
suffix++; suffix++;
@ -557,9 +574,9 @@ namespace Fungus
} }
} }
/** /// <summary>
* Returns a new Block key that is guaranteed not to clash with any existing Block in the Flowchart. /// Returns a new Block key that is guaranteed not to clash with any existing Block in the Flowchart.
*/ /// </summary>
public virtual string GetUniqueBlockKey(string originalKey, Block ignoreBlock = null) public virtual string GetUniqueBlockKey(string originalKey, Block ignoreBlock = null)
{ {
int suffix = 0; int suffix = 0;
@ -580,12 +597,12 @@ namespace Fungus
foreach(Block block in blocks) foreach(Block block in blocks)
{ {
if (block == ignoreBlock || if (block == ignoreBlock ||
block.blockName == null) block.BlockName == null)
{ {
continue; continue;
} }
if (block.blockName.Equals(key, StringComparison.CurrentCultureIgnoreCase)) if (block.BlockName.Equals(key, StringComparison.CurrentCultureIgnoreCase))
{ {
collision = true; collision = true;
suffix++; suffix++;
@ -600,9 +617,9 @@ namespace Fungus
} }
} }
/** /// <summary>
* Returns a new Label key that is guaranteed not to clash with any existing Label in the Block. /// Returns a new Label key that is guaranteed not to clash with any existing Label in the Block.
*/ /// </summary>
public virtual string GetUniqueLabelKey(string originalKey, Label ignoreLabel) public virtual string GetUniqueLabelKey(string originalKey, Label ignoreLabel)
{ {
int suffix = 0; int suffix = 0;
@ -614,13 +631,13 @@ namespace Fungus
baseKey = "New Label"; baseKey = "New Label";
} }
Block block = ignoreLabel.parentBlock; Block block = ignoreLabel.ParentBlock;
string key = baseKey; string key = baseKey;
while (true) while (true)
{ {
bool collision = false; bool collision = false;
foreach(Command command in block.commandList) foreach(Command command in block.CommandList)
{ {
Label label = command as Label; Label label = command as Label;
if (label == null || if (label == null ||
@ -629,7 +646,7 @@ namespace Fungus
continue; continue;
} }
if (label.key.Equals(key, StringComparison.CurrentCultureIgnoreCase)) if (label.Key.Equals(key, StringComparison.CurrentCultureIgnoreCase))
{ {
collision = true; collision = true;
suffix++; suffix++;
@ -643,19 +660,19 @@ namespace Fungus
} }
} }
} }
/** /// <summary>
* Returns the variable with the specified key, or null if the key is not found. /// Returns the variable with the specified key, or null if the key is not found.
* You will need to cast the returned variable to the correct sub-type. /// You will need to cast the returned variable to the correct sub-type.
* You can then access the variable's value using the Value property. e.g. /// You can then access the variable's value using the Value property. e.g.
* BooleanVariable boolVar = flowchart.GetVariable("MyBool") as BooleanVariable; /// BooleanVariable boolVar = flowchart.GetVariable("MyBool") as BooleanVariable;
* boolVar.Value = false; /// boolVar.Value = false;
*/ /// </summary>
public Variable GetVariable(string key) public Variable GetVariable(string key)
{ {
foreach (Variable variable in variables) foreach (Variable variable in variables)
{ {
if (variable != null && variable.key == key) if (variable != null && variable.Key == key)
{ {
return variable; return variable;
} }
@ -664,17 +681,17 @@ namespace Fungus
return null; return null;
} }
/** /// <summary>
* Returns the variable with the specified key, or null if the key is not found. /// Returns the variable with the specified key, or null if the key is not found.
* You can then access the variable's value using the Value property. e.g. /// You can then access the variable's value using the Value property. e.g.
* BooleanVariable boolVar = flowchart.GetVariable<BooleanVariable>("MyBool"); /// BooleanVariable boolVar = flowchart.GetVariable<BooleanVariable>("MyBool");
* boolVar.Value = false; /// boolVar.Value = false;
*/ /// </summary>
public T GetVariable<T>(string key) where T : Variable public T GetVariable<T>(string key) where T : Variable
{ {
foreach (Variable variable in variables) foreach (Variable variable in variables)
{ {
if (variable != null && variable.key == key) if (variable != null && variable.Key == key)
{ {
return variable as T; return variable as T;
} }
@ -684,15 +701,15 @@ namespace Fungus
return null; return null;
} }
/** /// <summary>
* Register a new variable with the Flowchart at runtime. /// Register a new variable with the Flowchart at runtime.
* The variable should be added as a component on the Flowchart game object. /// The variable should be added as a component on the Flowchart game object.
*/ /// </summary>
public void SetVariable<T>(string key, T newvariable) where T : Variable public void SetVariable<T>(string key, T newvariable) where T : Variable
{ {
foreach (Variable v in variables) foreach (Variable v in variables)
{ {
if (v != null && v.key == key) if (v != null && v.Key == key)
{ {
T variable = v as T; T variable = v as T;
if (variable != null) if (variable != null)
@ -706,15 +723,15 @@ namespace Fungus
Debug.LogWarning("Variable " + key + " not found."); Debug.LogWarning("Variable " + key + " not found.");
} }
/** /// <summary>
* Gets a list of all variables with public scope in this Flowchart. /// Gets a list of all variables with public scope in this Flowchart.
*/ /// </summary>
public virtual List<Variable> GetPublicVariables() public virtual List<Variable> GetPublicVariables()
{ {
List<Variable> publicVariables = new List<Variable>(); List<Variable> publicVariables = new List<Variable>();
foreach (Variable v in variables) foreach (Variable v in variables)
{ {
if (v != null && v.scope == VariableScope.Public) if (v != null && v.Scope == VariableScope.Public)
{ {
publicVariables.Add(v); publicVariables.Add(v);
} }
@ -723,17 +740,17 @@ namespace Fungus
return publicVariables; return publicVariables;
} }
/** /// <summary>
* Gets the value of a boolean variable. /// Gets the value of a boolean variable.
* Returns false if the variable key does not exist. /// Returns false if the variable key does not exist.
*/ /// </summary>
public virtual bool GetBooleanVariable(string key) public virtual bool GetBooleanVariable(string key)
{ {
BooleanVariable variable = GetVariable<BooleanVariable>(key); BooleanVariable variable = GetVariable<BooleanVariable>(key);
if(variable != null) if(variable != null)
{ {
return GetVariable<BooleanVariable>(key).value; return GetVariable<BooleanVariable>(key).Value;
} }
else else
{ {
@ -741,30 +758,30 @@ namespace Fungus
} }
} }
/** /// <summary>
* Sets the value of a boolean variable. /// Sets the value of a boolean variable.
* The variable must already be added to the list of variables for this Flowchart. /// The variable must already be added to the list of variables for this Flowchart.
*/ /// </summary>
public virtual void SetBooleanVariable(string key, bool value) public virtual void SetBooleanVariable(string key, bool value)
{ {
BooleanVariable variable = GetVariable<BooleanVariable>(key); BooleanVariable variable = GetVariable<BooleanVariable>(key);
if(variable != null) if(variable != null)
{ {
variable.value = value; variable.Value = value;
} }
} }
/** /// <summary>
* Gets the value of an integer variable. /// Gets the value of an integer variable.
* Returns 0 if the variable key does not exist. /// Returns 0 if the variable key does not exist.
*/ /// </summary>
public virtual int GetIntegerVariable(string key) public virtual int GetIntegerVariable(string key)
{ {
IntegerVariable variable = GetVariable<IntegerVariable>(key); IntegerVariable variable = GetVariable<IntegerVariable>(key);
if (variable != null) if (variable != null)
{ {
return GetVariable<IntegerVariable>(key).value; return GetVariable<IntegerVariable>(key).Value;
} }
else else
{ {
@ -772,30 +789,30 @@ namespace Fungus
} }
} }
/** /// <summary>
* Sets the value of an integer variable. /// Sets the value of an integer variable.
* The variable must already be added to the list of variables for this Flowchart. /// The variable must already be added to the list of variables for this Flowchart.
*/ /// </summary>
public virtual void SetIntegerVariable(string key, int value) public virtual void SetIntegerVariable(string key, int value)
{ {
IntegerVariable variable = GetVariable<IntegerVariable>(key); IntegerVariable variable = GetVariable<IntegerVariable>(key);
if (variable != null) if (variable != null)
{ {
variable.value = value; variable.Value = value;
} }
} }
/** /// <summary>
* Gets the value of a float variable. /// Gets the value of a float variable.
* Returns 0 if the variable key does not exist. /// Returns 0 if the variable key does not exist.
*/ /// </summary>
public virtual float GetFloatVariable(string key) public virtual float GetFloatVariable(string key)
{ {
FloatVariable variable = GetVariable<FloatVariable>(key); FloatVariable variable = GetVariable<FloatVariable>(key);
if (variable != null) if (variable != null)
{ {
return GetVariable<FloatVariable>(key).value; return GetVariable<FloatVariable>(key).Value;
} }
else else
{ {
@ -803,30 +820,30 @@ namespace Fungus
} }
} }
/** /// <summary>
* Sets the value of a float variable. /// Sets the value of a float variable.
* The variable must already be added to the list of variables for this Flowchart. /// The variable must already be added to the list of variables for this Flowchart.
*/ /// </summary>
public virtual void SetFloatVariable(string key, float value) public virtual void SetFloatVariable(string key, float value)
{ {
FloatVariable variable = GetVariable<FloatVariable>(key); FloatVariable variable = GetVariable<FloatVariable>(key);
if (variable != null) if (variable != null)
{ {
variable.value = value; variable.Value = value;
} }
} }
/** /// <summary>
* Gets the value of a string variable. /// Gets the value of a string variable.
* Returns the empty string if the variable key does not exist. /// Returns the empty string if the variable key does not exist.
*/ /// </summary>
public virtual string GetStringVariable(string key) public virtual string GetStringVariable(string key)
{ {
StringVariable variable = GetVariable<StringVariable>(key); StringVariable variable = GetVariable<StringVariable>(key);
if (variable != null) if (variable != null)
{ {
return GetVariable<StringVariable>(key).value; return GetVariable<StringVariable>(key).Value;
} }
else else
{ {
@ -834,22 +851,22 @@ namespace Fungus
} }
} }
/** /// <summary>
* Sets the value of a string variable. /// Sets the value of a string variable.
* The variable must already be added to the list of variables for this Flowchart. /// The variable must already be added to the list of variables for this Flowchart.
*/ /// </summary>
public virtual void SetStringVariable(string key, string value) public virtual void SetStringVariable(string key, string value)
{ {
StringVariable variable = GetVariable<StringVariable>(key); StringVariable variable = GetVariable<StringVariable>(key);
if (variable != null) if (variable != null)
{ {
variable.value = value; variable.Value = value;
} }
} }
/** /// <summary>
* Set the block objects to be hidden or visible depending on the hideComponents property. /// Set the block objects to be hidden or visible depending on the hideComponents property.
*/ /// </summary>
public virtual void UpdateHideFlags() public virtual void UpdateHideFlags()
{ {
if (hideComponents) if (hideComponents)
@ -893,11 +910,17 @@ namespace Fungus
} }
/// <summary>
/// Clears the list of selected commands.
/// </summary>
public virtual void ClearSelectedCommands() public virtual void ClearSelectedCommands()
{ {
selectedCommands.Clear(); selectedCommands.Clear();
} }
/// <summary>
/// Adds a command to the list of selected commands.
/// </summary>
public virtual void AddSelectedCommand(Command command) public virtual void AddSelectedCommand(Command command)
{ {
if (!selectedCommands.Contains(command)) if (!selectedCommands.Contains(command))
@ -906,6 +929,9 @@ namespace Fungus
} }
} }
/// <summary>
/// Reset the commands and variables in the Flowchart.
/// </summary>
public virtual void Reset(bool resetCommands, bool resetVariables) public virtual void Reset(bool resetCommands, bool resetVariables)
{ {
if (resetCommands) if (resetCommands)
@ -926,9 +952,9 @@ namespace Fungus
} }
} }
/** /// <summary>
* Override this in a Flowchart subclass to filter which commands are shown in the Add Command list. /// Override this in a Flowchart subclass to filter which commands are shown in the Add Command list.
*/ /// </summary>
public virtual bool IsCommandSupported(CommandInfoAttribute commandInfo) public virtual bool IsCommandSupported(CommandInfoAttribute commandInfo)
{ {
foreach (string key in hideCommands) foreach (string key in hideCommands)
@ -944,9 +970,9 @@ namespace Fungus
return true; return true;
} }
/** /// <summary>
* Returns true if there are any executing blocks in this Flowchart. /// Returns true if there are any executing blocks in this Flowchart.
*/ /// </summary>
public virtual bool HasExecutingBlocks() public virtual bool HasExecutingBlocks()
{ {
Block[] blocks = GetComponents<Block>(); Block[] blocks = GetComponents<Block>();
@ -960,9 +986,9 @@ namespace Fungus
return false; return false;
} }
/** /// <summary>
* Returns a list of all executing blocks in this Flowchart. /// Returns a list of all executing blocks in this Flowchart.
*/ /// </summary>
public virtual List<Block> GetExecutingBlocks() public virtual List<Block> GetExecutingBlocks()
{ {
List<Block> executingBlocks = new List<Block>(); List<Block> executingBlocks = new List<Block>();
@ -979,11 +1005,11 @@ namespace Fungus
return executingBlocks; return executingBlocks;
} }
/** /// <summary>
* Implementation of StringSubstituter.ISubstitutionHandler which matches any public variable in the Flowchart. /// Implementation of StringSubstituter.ISubstitutionHandler which matches any public variable in the Flowchart.
* To perform full variable substitution with all substitution handlers in the scene, you should /// To perform full variable substitution with all substitution handlers in the scene, you should
* use the SubstituteVariables() method instead. /// use the SubstituteVariables() method instead.
*/ /// </summary>
[MoonSharp.Interpreter.MoonSharpHidden] [MoonSharp.Interpreter.MoonSharpHidden]
public virtual bool SubstituteStrings(StringBuilder input) public virtual bool SubstituteStrings(StringBuilder input)
{ {
@ -1004,8 +1030,8 @@ namespace Fungus
if (variable == null) if (variable == null)
continue; continue;
if (variable.scope == VariableScope.Public && if (variable.Scope == VariableScope.Public &&
variable.key == key) variable.Key == key)
{ {
string value = variable.ToString(); string value = variable.ToString();
input.Replace(match.Value, value); input.Replace(match.Value, value);
@ -1018,12 +1044,12 @@ namespace Fungus
return modified; return modified;
} }
/** /// <summary>
* Substitute variables in the input text with the format {$VarName} /// Substitute variables in the input text with the format {$VarName}
* This will first match with private variables in this Flowchart, and then /// This will first match with private variables in this Flowchart, and then
* with public variables in all Flowcharts in the scene (and any component /// with public variables in all Flowcharts in the scene (and any component
* in the scene that implements StringSubstituter.ISubstitutionHandler). /// in the scene that implements StringSubstituter.ISubstitutionHandler).
*/ /// </summary>
public virtual string SubstituteVariables(string input) public virtual string SubstituteVariables(string input)
{ {
if (stringSubstituer == null) if (stringSubstituer == null)
@ -1032,7 +1058,7 @@ namespace Fungus
} }
// Use the string builder from StringSubstituter for efficiency. // Use the string builder from StringSubstituter for efficiency.
StringBuilder sb = stringSubstituer.stringBuilder; StringBuilder sb = stringSubstituer._StringBuilder;
sb.Length = 0; sb.Length = 0;
sb.Append(input); sb.Append(input);
@ -1053,8 +1079,8 @@ namespace Fungus
if (variable == null) if (variable == null)
continue; continue;
if (variable.scope == VariableScope.Private && if (variable.Scope == VariableScope.Private &&
variable.key == key) variable.Key == key)
{ {
string value = variable.ToString(); string value = variable.ToString();
sb.Replace(match.Value, value); sb.Replace(match.Value, value);
@ -1076,5 +1102,4 @@ namespace Fungus
} }
} }
} }
} }

18
Assets/Fungus/Flowchart/Scripts/FungusState.cs

@ -1,20 +1,18 @@
/** // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
using UnityEngine; using UnityEngine;
using System.Collections;
namespace Fungus namespace Fungus
{ {
/// <summary>
// Used by the Flowchart window to serialize the currently active Flowchart object /// Used by the Flowchart window to serialize the currently active Flowchart object
// so that the same Flowchart can be displayed while editing & playing. /// so that the same Flowchart can be displayed while editing & playing.
/// </summary>
[AddComponentMenu("")] [AddComponentMenu("")]
public class FungusState : MonoBehaviour public class FungusState : MonoBehaviour
{ {
public Flowchart selectedFlowchart; [SerializeField] protected Flowchart selectedFlowchart;
public Flowchart SelectedFlowchart { get { return selectedFlowchart; } set { selectedFlowchart = value; } }
} }
} }

15
Assets/Fungus/Flowchart/Scripts/Node.cs

@ -1,18 +1,17 @@
/** // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
using UnityEngine; using UnityEngine;
using System.Collections;
namespace Fungus namespace Fungus
{ {
/// <summary>
/// Base class for Flowchart nodes.
/// </summary>
[AddComponentMenu("")] [AddComponentMenu("")]
public class Node : MonoBehaviour public class Node : MonoBehaviour
{ {
public Rect nodeRect = new Rect(0, 0, 120, 30); [SerializeField] protected Rect nodeRect = new Rect(0, 0, 120, 30);
public Rect _NodeRect { get { return nodeRect; } set { nodeRect = value; } }
} }
} }

29
Assets/Fungus/Flowchart/Scripts/SceneLoader.cs

@ -1,7 +1,5 @@
/** // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
using UnityEngine; using UnityEngine;
#if UNITY_5_0 || UNITY_5_1 || UNITY_5_2 #if UNITY_5_0 || UNITY_5_1 || UNITY_5_2
@ -9,27 +7,26 @@
using UnityEngine.SceneManagement; using UnityEngine.SceneManagement;
#endif #endif
using System.Collections; using System.Collections;
using System;
namespace Fungus namespace Fungus
{ {
/** /// <summary>
* Helper component for loading a new scene. /// Helper component for loading a new scene.
* A fullscreen loading image is displayed while loading the new scene. /// A fullscreen loading image is displayed while loading the new scene.
* All Rooms are destroyed and unused assets are released from memory before loading the new scene to minimize memory footprint. /// All Rooms are destroyed and unused assets are released from memory before loading the new scene to minimize memory footprint.
* For streaming Web Player builds, the loading image will be displayed until the requested level has finished downloading. /// For streaming Web Player builds, the loading image will be displayed until the requested level has finished downloading.
*/ /// </summary>
public class SceneLoader : MonoBehaviour public class SceneLoader : MonoBehaviour
{ {
protected Texture2D loadingTexture; protected Texture2D loadingTexture;
protected string sceneToLoad; protected string sceneToLoad;
protected bool displayedImage; protected bool displayedImage;
/** /// <summary>
* Asynchronously load a new scene. /// Asynchronously load a new scene.
* @param _sceneToLoad The name of the scene to load. Scenes must be added in project build settings. /// </summary>
* @param _loadingTexture Loading image to display while loading the new scene. /// <param name="_sceneToLoad">The name of the scene to load. Scenes must be added in project build settings.</param>
*/ /// <param name="_loadingTexture">Loading image to display while loading the new scene.</param>
static public void LoadScene(string _sceneToLoad, Texture2D _loadingTexture) static public void LoadScene(string _sceneToLoad, Texture2D _loadingTexture)
{ {
// Unity does not provide a way to check if the named scene actually exists in the project. // Unity does not provide a way to check if the named scene actually exists in the project.

15
Assets/Fungus/Flowchart/Scripts/StringFormatter.cs

@ -1,16 +1,14 @@
/** // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
using UnityEngine;
using System.IO;
using System.Collections;
using System.Text; using System.Text;
using System; using System;
namespace Fungus namespace Fungus
{ {
/// <summary>
/// Misc string formatting functions.
/// </summary>
public class StringFormatter public class StringFormatter
{ {
public static string[] FormatEnumNames(Enum e, string firstLabel) public static string[] FormatEnumNames(Enum e, string firstLabel)
@ -58,6 +56,5 @@ namespace Fungus
} }
return true; return true;
} }
} }
} }

38
Assets/Fungus/Flowchart/Scripts/Variable.cs

@ -1,21 +1,23 @@
/** // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
using UnityEngine; using UnityEngine;
using System; using System;
using System.Collections;
using System.Collections.Generic;
namespace Fungus namespace Fungus
{ {
/// <summary>
/// Scope types for Variables.
/// </summary>
public enum VariableScope public enum VariableScope
{ {
Private, Private,
Public Public
} }
/// <summary>
/// Attribute class for variables.
/// </summary>
public class VariableInfoAttribute : Attribute public class VariableInfoAttribute : Attribute
{ {
public VariableInfoAttribute(string category, string variableType, int order = 0) public VariableInfoAttribute(string category, string variableType, int order = 0)
@ -30,6 +32,9 @@ namespace Fungus
public int Order { get; set; } public int Order { get; set; }
} }
/// <summary>
/// Attribute class for variable properties.
/// </summary>
public class VariablePropertyAttribute : PropertyAttribute public class VariablePropertyAttribute : PropertyAttribute
{ {
public VariablePropertyAttribute (params System.Type[] variableTypes) public VariablePropertyAttribute (params System.Type[] variableTypes)
@ -48,36 +53,45 @@ namespace Fungus
public System.Type[] VariableTypes { get; set; } public System.Type[] VariableTypes { get; set; }
} }
/// <summary>
/// Abstract base class for variables.
/// </summary>
[RequireComponent(typeof(Flowchart))] [RequireComponent(typeof(Flowchart))]
public abstract class Variable : MonoBehaviour public abstract class Variable : MonoBehaviour
{ {
public VariableScope scope; [SerializeField] protected VariableScope scope;
public VariableScope Scope { get { return scope; } }
public string key = ""; [SerializeField] protected string key = "";
public string Key { get { return key; } set { key = value; } }
public abstract void OnReset(); public abstract void OnReset();
} }
/// <summary>
/// Generic concrete base class for variables.
/// </summary>
public abstract class VariableBase<T> : Variable public abstract class VariableBase<T> : Variable
{ {
public T value; [SerializeField] protected T value;
public T Value { get { return this.value; } set { this.value = value; } }
protected T startValue; protected T startValue;
public override void OnReset() public override void OnReset()
{ {
value = startValue; Value = startValue;
} }
public override string ToString() public override string ToString()
{ {
return value.ToString(); return Value.ToString();
} }
protected virtual void Start() protected virtual void Start()
{ {
// Remember the initial value so we can reset later on // Remember the initial value so we can reset later on
startValue = value; startValue = Value;
} }
} }
} }

20
Assets/Fungus/Flowchart/Scripts/VariableTypes/AnimatorVariable.cs

@ -1,19 +1,22 @@
/** // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
using UnityEngine; using UnityEngine;
using System.Collections;
namespace Fungus namespace Fungus
{ {
/// <summary>
/// Animator variable type.
/// </summary>
[VariableInfo("Other", "Animator")] [VariableInfo("Other", "Animator")]
[AddComponentMenu("")] [AddComponentMenu("")]
[System.Serializable] [System.Serializable]
public class AnimatorVariable : VariableBase<Animator> public class AnimatorVariable : VariableBase<Animator>
{} {}
/// <summary>
/// Container for an Animator variable reference or constant value.
/// </summary>
[System.Serializable] [System.Serializable]
public struct AnimatorData public struct AnimatorData
{ {
@ -37,8 +40,8 @@ namespace Fungus
public Animator Value public Animator Value
{ {
get { return (animatorRef == null) ? animatorVal : animatorRef.value; } get { return (animatorRef == null) ? animatorVal : animatorRef.Value; }
set { if (animatorRef == null) { animatorVal = value; } else { animatorRef.value = value; } } set { if (animatorRef == null) { animatorVal = value; } else { animatorRef.Value = value; } }
} }
public string GetDescription() public string GetDescription()
@ -49,9 +52,8 @@ namespace Fungus
} }
else else
{ {
return animatorRef.key; return animatorRef.Key;
} }
} }
} }
} }

20
Assets/Fungus/Flowchart/Scripts/VariableTypes/AudioSourceVariable.cs

@ -1,19 +1,22 @@
/** // This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus).
* This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
* It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE)
*/
using UnityEngine; using UnityEngine;
using System.Collections;
namespace Fungus namespace Fungus
{ {
/// <summary>
/// AudioSource variable type.
/// </summary>
[VariableInfo("Other", "AudioSource")] [VariableInfo("Other", "AudioSource")]
[AddComponentMenu("")] [AddComponentMenu("")]
[System.Serializable] [System.Serializable]
public class AudioSourceVariable : VariableBase<AudioSource> public class AudioSourceVariable : VariableBase<AudioSource>
{} {}
/// <summary>
/// Container for an AudioSource variable reference or constant value.
/// </summary>
[System.Serializable] [System.Serializable]
public struct AudioSourceData public struct AudioSourceData
{ {
@ -37,8 +40,8 @@ namespace Fungus
public AudioSource Value public AudioSource Value
{ {
get { return (audioSourceRef == null) ? audioSourceVal : audioSourceRef.value; } get { return (audioSourceRef == null) ? audioSourceVal : audioSourceRef.Value; }
set { if (audioSourceRef == null) { audioSourceVal = value; } else { audioSourceRef.value = value; } } set { if (audioSourceRef == null) { audioSourceVal = value; } else { audioSourceRef.Value = value; } }
} }
public string GetDescription() public string GetDescription()
@ -49,9 +52,8 @@ namespace Fungus
} }
else else
{ {
return audioSourceRef.key; return audioSourceRef.Key;
} }
} }
} }
} }

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save