Menu Stack
Namespace: HotChocolate.UI; Inherits from: MonoBehaviour
Properties
menuAnchor |
The RectTransform to use as a parent for the menu instances. |
inputBlocker |
A gameobject to activate in between menu phases to prevent button mashing. Optional. |
OnMenuPushed |
An event that fires anytime a menu is pushed on the stack. Can occur with the Push and Jump methods. |
OnMenuPopped |
An event that fires anytime a menu is popped from the stack. Can occur with the Pop, PopAllAbove, PopAll, and Jump methods. |
OnMenuFocusChanged |
Invoked when a menu gains or loses focus. |
createInstanceDefault |
The default method to instantiate a menu. Default value is Menu.CreateInstanceFromPrefab. |
destroyInstanceDefault |
The default method to destroy a menu instance. Default value is Menu.DestroyPrefabInstance. |
playPushAnimationDefault |
The default animation function to play when a menu is pushed on the stack. Default value is Menu.PlayPushAnimationDefault. |
playPopAnimationDefault |
The default animation function to play when a menu is popped from the stack. Default value is Menu.PlayPopAnimationDefault. |
playFocusInAnimationDefault |
The default animation function to play when a menu gets focussed in. Only plays if the menu wasn't pushed. Default value is Menu.PlayFocusInAnimationDefault. |
playFocusOutAnimationDefault |
The default animation function to play when a menu gets focussed out. Only plays if the menu wasn't popped. Default value is Menu.NoAnimation. |
Methods
Count |
Returns the number of menu instances in the stack. |
Find |
Returns the menu instance with the given id. Returns null if not found. |
Top |
Returns the topmost menu instance. Returns null if stack is empty. |
Push |
Instantiates a new menu and adds it on top of the stack. |
Jump |
Pops to a given menu in the stack and pushes a new instance. |
Pop |
Removes the top instance from the stack and destroys it. |
PopAllAbove |
Pops all menus above a given menu. |
PopAll |
Pops all menus from the stack. |
Description
The MenuStack is a MonoBehaviour that allows to instantiate UGUI menus asynchronously in the form of a stack. It supports Addressables. Menus need to implement IMenu.
Usage
using HotChocolate.UI;
using UnityEngine;
namespace HotChocolate.Samples.MenuTest
{
public class TestMenu : MonoBehaviour
{
public MenuStack menuStack;
public GenericPrompt promptPrefab;
public void Push(string id)
{
menuStack.Push(promptPrefab, id, GetPromptData(id));
}
public void Pop()
{
menuStack.Pop();
}
public void Jump(string id, string fromId)
{
menuStack.Jump(promptPrefab, id, fromId, GetPromptData(id));
}
public void PopAllAbove(string id)
{
menuStack.PopAllAbove(id);
}
public void PopAll()
{
menuStack.PopAll();
}
}
}
Namespace: HotChocolate.UI
Interface
Id |
The menu instance id that will be set by the MenuStack. |
HasFocus |
Does this menu has focus. Set by the MenuStack. |
BeforeFocusIn |
A function that will be called right before the menu instance gets focussed in. Suggested value: Menu.ActivateInstance. |
AfterFocusOut |
A function that will be called right after the menu instance gets focussed out. Suggested value: Menu.DeactivateInstance. |
OnPush |
Will be called when the menu is pushed. Happens before focus in and before the in animation starts. |
OnPop |
Will be called when the menu is popped. Happens after focus out and after the out animation finished. |
OnFocusIn |
Will be called when the menu gains focus. Happens before the in animation starts. |
OnFocusOut |
Will be called when the menu looses focus. Happens before the out animation starts. |
Description
In order to use the MenuStack, your menu prefab must implement IMenu.
public void Push(object menuAsset, string menuId, object data = null)
public void Push(object menuAsset, string menuId, Menu.CreateInstance createInstanceTask, object data = null)
public void Push(object menuAsset, string menuId, Menu.PlayOutAnimation playFocusOutAnimationTask, Menu.CreateInstance createInstanceTask, Menu.PlayInAnimation playPushAnimationTask, object data = null)
Parameters
menuAsset |
The prefab or addressable key to instantiate. The prefab that is referenced must implement IMenu. |
menuId |
The id to be associated to the new instance. |
playFocusOutAnimationTask |
The animation function to play on the menu that would focus out. Default value: MenuStack.playFocusOutAnimationDefault. |
createInstanceTask |
The function used to instantiate this menu. Default value: MenuStack.createInstanceDefault. |
playPushAnimationTask |
The animation function to play on the menu that will be pushed. Default value: MenuStack.playPushAnimationDefault. |
data |
Anything you want to pass to the new menu instance. |
Description
Instantiates a new menu using the createInstanceTask function and adds it on top of the stack.
Does nothing if the menuId already exists in the stack.
public void Jump(object menuAsset, string menuId, string fromMenu, object data = null)
public void Jump(object menuAsset, string menuId, string fromMenu, Menu.CreateInstance createInstanceTask, object data = null)
public void Jump(object menuAsset, string menuId, string fromMenu, Menu.PlayOutAnimation playFocusOutAnimationTask, Menu.DestroyInstance destroyInstanceTask, Menu.CreateInstance createInstanceTask, Menu.PlayInAnimation playPushAnimationTask, object data = null)
Parameters
menuAsset |
The prefab or addressable key to instantiate. The prefab that is referenced must implement IMenu. |
menuId |
The id to be associated to the new instance. |
fromMenu |
The id of the menu to push from. |
playFocusOutAnimationTask |
The animation function to play on the menu that would focus out. Default value: MenuStack.playFocusOutAnimationDefault. |
destroyInstanceTask |
The function used to destroy menu instances. Default value: MenuStack.destroyInstanceDefault. |
createInstanceTask |
The function used to instantiate this menu. Default value: MenuStack.createInstanceDefault. |
playPushAnimationTask |
The animation function to play on the menu that will be pushed. Default value: MenuStack.playPushAnimationDefault. |
data |
Anything you want to pass to the new menu instance. |
Description
If fromMenu is not null or empty, pops all above fromMenu and pushes new menu. If fromMenu is null or empty, pops all and pushes new menu. If the menuId already exists in the stack, pops all above it.
Does nothing if fromMenu is not null or empty and doesn't exist in the stack.
public void Pop()
public void Pop(Menu.PlayOutAnimation playPopAnimationTask, Menu.PlayInAnimation playFocusInAnimationTask)
public void Pop(Menu.PlayOutAnimation playPopAnimationTask, Menu.PlayInAnimation playFocusInAnimationTask, Menu.DestroyInstance destroyInstanceTask)
Parameters
Description
Removes and destroys the topmost menu instance.
Does nothing if stack is empty.
public void PopAllAbove(string menuId)
public void PopAllAbove(string menuId, Menu.PlayOutAnimation playPopAnimationTask, Menu.PlayInAnimation playFocusInAnimationTask)
public void PopAllAbove(string menuId, Menu.PlayOutAnimation playPopAnimationTask, Menu.PlayInAnimation playFocusInAnimationTask, Menu.DestroyInstance destroyInstanceTask)
Parameters
Description
Removes and destroys all menu instances above menuId.
Does nothing if menuId doesn't exist in the stack.
public void PopAll()
public void PopAll(Menu.PlayOutAnimation playPopAnimationTask)
public void PopAll(Menu.PlayOutAnimation playPopAnimationTask, Menu.DestroyInstance destroyInstanceTask)
Parameters
Description
Removes and destroys all menu instances from the stack.
public static void ActivateInstance(IMenu instance)
Parameters
instance |
An instance of IMenu. |
Description
Activates the menu GameObject. Is meant to be used as default value for IMenu BeforeFocusIn property.
public static void DeactivateInstance(IMenu instance)
Parameters
instance |
An instance of IMenu. |
Description
Deactivates the menu GameObject. Is meant to be used as default value for IMenu AfterFocusOut property.
public static Task<IMenu> CreateInstanceFromPrefab(object prefab, string menuId, Transform parent, MonoBehaviour opHolder)
Parameters
prefab |
The prefab to instantiate. It must implement IMenu. |
menuId |
The id to be associated to the new instance. |
parent |
The RectTransform to be the parent of the menu instance. |
opHolder |
The MenuStack itself as a MonoBehaviour, used for Unity async operations. |
Description
Instantiates a menu prefab and sets its id to menuId.
public static Task DestroyPrefabInstance(IMenu instance, MonoBehaviour opHolder)
Parameters
instance |
The prefab instance to be destroyed. |
opHolder |
The MenuStack itself as a MonoBehaviour, used for Unity async operations. |
Description
Destroys a menu instance.
public static Task<IMenu> CreateInstanceFromAddressable(object assetKey, string menuId, Transform parent, MonoBehaviour opHolder)
Parameters
assetKey |
The Addressable key that references the prefab. The prefab must implement IMenu. |
menuId |
The id to be associated to the new instance. |
parent |
The RectTransform to be the parent of the menu instance. |
opHolder |
The MenuStack itself as a MonoBehaviour, used for Unity async operations. |
Description
Instantiates a menu prefab using an Addressable key and sets its id to menuId.
public static Task DestroyAddressableInstance(IMenu instance, MonoBehaviour opHolder)
Parameters
instance |
The prefab instance to be destroyed. |
opHolder |
The MenuStack itself as a MonoBehaviour, used for Unity async operations. |
Description
Destroys a menu instance using the Addressable system.
public static void UseAddressables(MenuStack menuStack)
Parameters
Description
Sets the menu stack createInstanceDefault and destroyInstanceDefault functions to use Menu.CreateInstanceFromAddressable and Menu.DestroyAddressableInstance.
Using the default animation functions allows for fast integration of various motions on different parts of your menu. Those default functions will search for IMenuAnimation components in the children of your menu instance.
Namespace: HotChocolate.UI
Interface
PushAnimation |
The async task to play when the menu is pushed. |
PopAnimation |
The async task to play when the menu is popped. |
FocusInAnimation |
The async task to play when the menu gets focus in and wasn't pushed. |
FocusOutAnimation |
The async task to play when the menu gets focus out and wasn't popped. |
Description
The interface used to create various menu animations. Already defined for you are: BouncyPanel, SlidingPanel, and FadingPanel.
public static async Task PlayPushAnimationDefault(IMenu instance)
Parameters
instance |
The instance of the menu the animation will play on. |
Description
Searches for IMenuAnimation components in the menu's children and executes PushAnimation on all of them simultaneously.
public static async Task PlayPopAnimationDefault(IMenu instance)
Parameters
instance |
The instance of the menu the animation will play on. |
Description
Searches for IMenuAnimation components in the menu's children and executes PopAnimation on all of them simultaneously.
public static async Task PlayFocusInAnimationDefault(IMenu instance)
Parameters
instance |
The instance of the menu the animation will play on. |
Description
Searches for IMenuAnimation components in the menu's children and executes FocusInAnimation on all of them simultaneously.
public static async Task PlayFocusOutAnimationDefault(IMenu instance)
Parameters
instance |
The instance of the menu the animation will play on. |
Description
Searches for IMenuAnimation components in the menu's children and executes FocusOutAnimation on all of them simultaneously.
public static async Task NoAnimation(IMenu instance)
Parameters
instance |
The instance of the menu the animation will play on. |
Description
Will play nothing.
Namespace: HotChocolate.UI.MenuAnimations; Inherits from: MonoBehaviour, IMenuAnimation
Properties
pushDelay |
Time in seconds to wait before playing the push animation. |
popDelay |
Time in seconds to wait before playing the pop animation. |
focusInDelay |
Time in seconds to wait before playing the focus in animation. |
focusOutDelay |
Time in seconds to wait before playing the focus out animation. |
pushConfig |
The BouncyPanelConfig asset to use for both push and pop animations. |
focusConfig |
The BouncyPanelConfig asset to use for both focus in and focus out animations. |
Description
Plays a bouncy animation on the gameobject it's put on.
Namespace: HotChocolate.UI.MenuAnimations; Inherits from: ScriptableObject
Properties
inAnimationDuration |
The duration in seconds of the push or focus in animation. |
inScaleStart |
The starting scale of the bounce in the push or focus in animation. |
inScaleMax |
The scale at the peak of the bounce in the push or focus in animation. |
inDelay |
The time in seconds to wait before playing the push or focus in animation. |
inAnimationEasing |
The tween function to use during the growing phase of the bounce in the push or focus in animation. |
inAnimationSettleEasing |
The tween function to use during the settle phase of the bounce in the push or focus in animation. |
outAnimationDuration |
The duration in seconds of the pop or focus out animation. |
outScaleMax |
The scale at the peak of the bounce in the pop or focus out animation. |
outScaleEnd |
The scale at the end of the bounce in the pop or focus out animation. |
outDelay |
The time in seconds to wait before playing the pop or focus out animation. |
outAnimationEasing |
The tween function to use during the growing phase of the bounce in the pop or focus out animation. |
outAnimationSettleEasing |
The tween function to use during the settle phase of the bounce in the pop or focus out animation. |
Tip
Try BouncyPanel on popups and buttons for a lively or cartoony effect!
Namespace: HotChocolate.UI.MenuAnimations; Inherits from: MonoBehaviour, IMenuAnimation
Properties
pushDelay |
Time in seconds to wait before playing the push animation. |
popDelay |
Time in seconds to wait before playing the pop animation. |
focusInDelay |
Time in seconds to wait before playing the focus in animation. |
focusOutDelay |
Time in seconds to wait before playing the focus out animation. |
pushConfig |
The SlidingPanelConfig asset to use for both push and pop animations. |
focusConfig |
The SlidingPanelConfig asset to use for both focus in and focus out animations. |
Description
Plays a sliding animation on the gameobject it's put on.
Namespace: HotChocolate.UI.MenuAnimations; Inherits from: ScriptableObject
Properties
inAnimationDuration |
The duration in seconds of the push or focus in animation. |
inStartPositionOffset |
The position offset at the start of the push or focus in animation. |
inDelay |
The time in seconds to wait before playing the push or focus in animation. |
inAnimationEasing |
The tween function to use during the push or focus in animation. |
outAnimationDuration |
The duration in seconds of the pop or focus out animation. |
outEndPositionOffset |
The position offset at the end of the pop or focus out animation. |
outDelay |
The time in seconds to wait before playing the pop or focus out animation. |
outAnimationEasing |
The tween function to use during the pop or focus out animation. |
Namespace: HotChocolate.UI.MenuAnimations; Inherits from: MonoBehaviour, IMenuAnimation
Properties
pushDelay |
Time in seconds to wait before playing the push animation. |
popDelay |
Time in seconds to wait before playing the pop animation. |
focusInDelay |
Time in seconds to wait before playing the focus in animation. |
focusOutDelay |
Time in seconds to wait before playing the focus out animation. |
pushConfig |
The FadingPanelConfig asset to use for both push and pop animations. |
focusConfig |
The FadingPanelConfig asset to use for both focus in and focus out animations. |
Description
Plays a fade in or fade out animation on the gameobject it's put on. Requires a CanvasGroup.
Namespace: HotChocolate.UI.MenuAnimations; Inherits from: ScriptableObject
Properties
fadeInDuration |
The duration in seconds of the push or focus in animation. |
inAlphaStart |
The starting alpha of the fade in the push or focus in animation. |
inAlphaEnd |
The alpha at the end of the fade in the push or focus in animation. |
inDelay |
The time in seconds to wait before playing the push or focus in animation. |
inAnimationEasing |
The tween function to use during the push or focus in animation. |
fadeOutDuration |
The duration in seconds of the pop or focus out animation. |
outAlphaEnd |
The alpha at the end of the fade in the pop or focus out animation. |
outDelay |
The time in seconds to wait before playing the pop or focus out animation. |
outAnimationEasing |
The tween function to use during the pop or focus out animation. |
Tip
Find examples of menu animations in Assets->Menus->Prompts in the Sample Project!
Scene Stack
Namespace: HotChocolate.World; Inherits from: MonoBehaviour
Properties
OnScenePushed |
An event that fires anytime a scene is pushed on the stack. Can occur with the Push and Jump methods. |
OnScenePopped |
An event that fires anytime a scene is popped from the stack. Can occur with the Pop, PopAllAbove, PopAll, and Jump methods. |
loadSceneDefault |
The default method to load a scene. Default value is Scene.LoadSceneDefault. |
unloadSceneDefault |
The default method to destroy unload a scene. Default value is Scene.UnloadSceneDefault. |
beforeFocusIn |
A function called before a scene gets focus in. Default value is Scene.ActivateScene. |
afterFocusOut |
A function called before a scene gets focus out. Default value is Scene.DeactivateScene. |
Methods
Count |
Returns the number of scenes in the stack. |
Find |
Returns the scene with the given name. Returns null if not found. |
Top |
Returns the topmost scene. Returns null if stack is empty. |
Push |
Loads a scene and adds it on top of the stack. |
Jump |
Pops to a given scene in the stack and pushes a new scene. |
Pop |
Removes and unloads the topmost scene. |
PopAllAbove |
Pops all scenes above a given scene. |
PopAll |
Pops all scenes from the stack. |
Description
The SceneStack is a MonoBehaviour that allows to load and unload Unity scenes asynchronously in the form of a stack. It works with both additive and single loading style. It supports Addressables.
Usage
using HotChocolate.World;
using UnityEngine;
namespace HotChocolate.Samples
{
[CreateAssetMenu(fileName = "SceneDefinition", menuName = "HotChocolate/Samples/Scene Definition", order = 1)]
public class SceneDefinition : ScriptableObject, ISceneDefinition
{
public string sceneName;
public string SceneName => sceneName;
public MenuDefinition hudMenu;
}
}
namespace HotChocolate.Samples
{
public class NavigationController : MonoBehaviour
{
public SceneStack SceneStack { get; private set; }
public async Task PushScene(SceneDefinition sceneDef, UnityEngine.SceneManagement.LoadSceneMode loadSceneMode)
{
await SceneStack.Push(sceneDef, loadSceneMode);
}
public async Task JumpToScene(SceneDefinition sceneDef, UnityEngine.SceneManagement.LoadSceneMode loadSceneMode)
{
await SceneStack.Jump(sceneDef, null, loadSceneMode);
}
public async Task PopScene()
{
await SceneStack.Pop();
}
}
}
Namespace: HotChocolate.World
Interface
SceneName |
The full path name of the scene. |
Description
In order to use the SceneStack, you need to create a class that implements ISceneDefinition.
Namespace: HotChocolate.World
Interface
SceneDef |
The ISceneDefinition associated to the loaded scene. |
Scene |
The loaded Unity scene. |
Description
Describes an instance of a scene on the stack.
public Task Push(ISceneDefinition sceneDef, LoadSceneMode loadSceneMode)
public Task Push(ISceneDefinition sceneDef, Scene.Load loadSceneTask, LoadSceneMode loadSceneMode)
Parameters
Description
Loads the scene using the loadSceneTask function and adds it on top of the stack.
Does nothing if the scene already exists in the stack.
public Task Jump(ISceneDefinition sceneDef, string fromSceneName, LoadSceneMode loadSceneMode)
public Task Jump(ISceneDefinition sceneDef, string fromSceneName, Scene.Unload unloadSceneTask, Scene.Load loadSceneTask, LoadSceneMode loadSceneMode)
Parameters
Description
If fromSceneName is not null or empty, pops all above fromSceneName and pushes new scene. If fromSceneName is null or empty, pops all and pushes new scene. If the sceneDef already exists in the stack, pops all above it.
Does nothing if fromSceneName is not null or empty and doesn't exist in the stack.
public Task Pop()
public Task Pop(Scene.Unload unloadSceneTask, Scene.Load loadSceneTask)
Parameters
Description
Removes and unloads the topmost scene. Loads the new topmost scene in single mode if isn't loaded.
Does nothing if the stack contains one or zero elements.
public Task PopAllAbove(string sceneName)
public Task PopAllAbove(string sceneName, Scene.Unload unloadSceneTask, Scene.Load loadSceneTask)
Parameters
Description
Removes and unloads all scenes above sceneName. Loads the new topmost scene in single mode if isn't loaded.
Does nothing if sceneName doesn't exist in the stack.
public Task PopAll()
public Task PopAll(Scene.Unload unloadSceneTask, Scene.Load loadSceneTask)
Parameters
Description
Removes and unloads all scenes from the stack above the very first one. Loads the new topmost scene in single mode if isn't loaded.
public static void ActivateScene(ISceneData sceneData)
Parameters
Description
Activates all the root GameObjects in the scene. Is the default value for the SceneStack beforeFocusIn property. Is useful only when loading scenes in additive mode.
public static void DeactivateScene(ISceneData sceneData)
Parameters
Description
Deactivates all the root GameObjects in the scene. Is the default value for the SceneStack afterFocusOut property. Is useful only when loading scenes in additive mode.
public static Task<ISceneData> LoadSceneDefault(ISceneDefinition sceneDef, LoadSceneMode loadSceneMode, MonoBehaviour opHolder)
Parameters
Description
Loads a scene from the sceneDef using the Unity Scene Manager. The scene name must be in the Build Settings for it to work.
public static Task UnloadSceneDefault(ISceneData sceneData, MonoBehaviour opHolder)
Parameters
sceneData |
The scene to unload. |
opHolder |
The SceneStack itself as a MonoBehaviour, used for Unity async operations. |
Description
Unloads a scene using the Unity Scene Manager.
public static Task<ISceneData> LoadSceneFromAddressable(ISceneDefinition sceneDef, LoadSceneMode loadSceneMode, MonoBehaviour opHolder)
Parameters
Description
Loads a scene using the Addressable system.
public static Task UnloadSceneFromAddressable(ISceneData sceneData, MonoBehaviour opHolder)
Parameters
sceneData |
The scene to unload. |
opHolder |
The SceneStack itself as a MonoBehaviour, used for Unity async operations. |
Description
Unloads a scene using the Addressable system.
public static void UseAddressables(SceneStack sceneStack)
Parameters
Description
Sets the scene stack loadSceneDefault and unloadSceneDefault functions to use Scene.LoadSceneFromAddressable and Scene.UnloadSceneFromAddressable.
The FTUE system allows you to create FtueEvents that contain a set of conditions and a sequence of steps to execute. All the boiler-plate work is already done for you so you can concentrate on writing steps and conditions that are specific to your game.
Tip
See how it's been used in the Sample Project Assets->Game! Read the code in Scripts/Game/FTUE!
Namespace: HotChocolate.FTUE
Interface
OnTriggered |
An event that fires when all conditions become true. |
Id |
A string to identify this event. |
Init |
Is called when added to the FtueListener. Takes an instance of an object as parameter that will be passed to conditions. |
ConditionIsTrue |
Returns true if the condition associated with the event is true. Returns false if condition is null. |
Execute |
Executes the sequence asynchronously. |
Dispose |
Cleans up the FtueEvent after use. |
ConditionsInstantiators |
Returns a list of Instantiators to be used by the editor to instantiate FtueConditions from your assembly. |
StepsInstantiators |
Returns a list of Instantiators to be used by the editor to instantiate FtueSteps from your assembly. |
Description
If for some reason you want to write your own FtueEvent, it must implement IFtueEvent.
Namespace: HotChocolate.FTUE;
Properties
displayName |
The name of class to instantiate. |
type |
The type of the class to instantiate. |
Instantiate |
A delegate that returns an instance of the class. |
Description
To be defined in a class that inherits from IFtueEvent to tell the editor how to instantiate the FtueSteps and FtueConditions specific to your game.
Namespace: HotChocolate.FTUE; Inherits from: ScriptableObject, IFtueEvent
Generics
TData |
An object that will be passed to both the sequence and conditions. |
TResult |
The object to be returned as the result of the sequence. Must implement IFtueResult. |
Properties
OnTriggered |
An event that fires when all conditions become true. |
Id |
The name given to this ScriptableObject instance. |
condition |
The condition that must be true for this event to be triggered. See FtueCompositeCondition. |
sequence |
The sequence of steps to execute. See FtueSequence. |
Methods
Init |
Is called when added to the FtueListener. Takes an instance of TData as parameter that will be passed to conditions. |
ConditionIsTrue |
Returns true if the condition associated with the event is true. Returns false if condition is null. |
Execute |
Executes the sequence asynchronously. |
Dispose |
Cleans up the FtueEvent after use. |
ConditionsInstantiators |
Returns a list of Instantiators to be used by the editor to instantiate FtueConditions from your assembly. |
StepsInstantiators |
Returns a list of Instantiators to be used by the editor to instantiate FtueSteps from your assembly. |
Description
A FtueEvent is a ScriptableObject that contains a FtueSequence to execute when the CompositeCondition is true. It works in tandem with the FtueListener.
Usage
using System;
using System.Collections.Generic;
using System.Linq;
using HotChocolate.FTUE;
using UnityEngine;
namespace HotChocolate.Samples.FTUE
{
[CreateAssetMenu(fileName = "FtueEvent", menuName = "HotChocolate/Samples/FTUE/Ftue Event", order = 1)]
public class FtueEvent : FtueEvent<Navigator, FtueResult>
{
private List<Instantiator> conditionsInstantiators = new List<Instantiator>();
private List<Instantiator> stepsInstantiators = new List<Instantiator>();
public override IEnumerable<Instantiator> ConditionsInstantiators()
{
conditionsInstantiators.Clear();
var conditionTypes = typeof(FtueEvent).Assembly.GetTypes().Where(t => t.BaseType == typeof(FtueCondition));
foreach (var stepType in conditionTypes)
{
conditionsInstantiators.Add(Create(stepType));
}
conditionsInstantiators.Add(Create(typeof(IFtueCondition).Assembly.GetTypes().FirstOrDefault(t => t == typeof(FtueCompositeCondition))));
return conditionsInstantiators;
}
public override IEnumerable<Instantiator> StepsInstantiators()
{
stepsInstantiators.Clear();
var stepTypes = typeof(FtueEvent).Assembly.GetTypes().Where(t => t.BaseType == typeof(FtueStep));
foreach(var stepType in stepTypes)
{
stepsInstantiators.Add(Create(stepType));
}
stepsInstantiators.Add(Create(typeof(IFtueStep).Assembly.GetTypes().FirstOrDefault(t => t == typeof(FtueSequence))));
return stepsInstantiators;
}
private Instantiator Create(Type type)
{
return new Instantiator()
{
displayName = type.Name,
type = type,
Instantiate = () => { return Activator.CreateInstance(type); }
};
}
}
}
public async Task<IFtueResult> Execute(IFtueResult result, object data, IFtueListener listener, CancellationToken ct)
Parameters
Description
Executes a FtueSequence. Returns the cumulated TResult.
Namespace: HotChocolate.FTUE
Interface
Description
If you want to write your own FtueListener, it must implement IFtueListener.
Namespace: HotChocolate.FTUE; Inherits from: MonoBehaviour, IFtueListener
Generics
Properties
OnEventStarted |
An event that fires before a FtueEvent gets executed. |
OnEventFinished |
An event that fires after a FtueEvent finishes. |
EventIsOngoing |
Returns true if at least one event was triggered and the FtueListener component is enabled. |
OngoingEvent |
The current active FtueEvent. Returns null if none. |
EventIsTriggered |
Takes a FtueEvent as parameter. Returns true if this event was triggered. Note that triggered does not necessarily means active, it means all the conditions were fullfilled and the event may eventually become active. |
EventIsPending |
Takes a FtueEvent as parameter. Returns true if this event can be triggered. |
Data |
The instance of TData to pass to FtueEvents. |
Methods
Description
A FtueListener is a MonoBehaviour that calls Execute on FtueEvents when their condition become true. Only one event plays at a time. If multiple events get triggered, they are queued. If a queued event no longer meets its condition, it will not play but will remain pending. The FtueListener also stores a list of IFtueElements that can be activated during FtueSteps.
Usage
using HotChocolate.FTUE;
namespace HotChocolate.Samples.FTUE
{
public class FtueResult : IFtueResult
{
public bool Failed { get; set; }
}
public class FtueListener : FtueListener<NavigationController, FtueResult>
{
}
}
public void RegisterElement(IFtueElement<TData, TResult> element)
Parameters
Description
The FtueListener keeps a list of IFtueElements that can be used by some IFtueSteps. Call this method to add an element to the list.
public void UnregisterElement(IFtueElement<TData, TResult> element)
Parameters
element |
The IFtueElement to remove from the registered list. |
Description
The FtueListener keeps a list of IFtueElements that can be used by some IFtueSteps. Call this method to remove an element from the list.
public IFtueElement<TData, TResult> GetElementToActivate(IFtueStep<TData, TResult> step)
Parameters
Description
Returns the first registered IFtueElement for which ShouldActivateFtue returns true.
public void AddEvent(FtueEvent<TData, TResult> evt)
Parameters
evt |
The FtueEvent to add to the list of pending events. |
Description
The FtueListener keeps a list of events that will be triggered when all their conditions become true. Call this method to add a FtueEvent to the list.
public void AddEvent(FtueEvent<TData, TResult> evt)
Parameters
evt |
The FtueEvent to remove from the list of pending events. |
Description
The FtueListener keeps a list of events that will be triggered when all their conditions become true. Call this method to remove a FtueEvent from the list.
Namespace: HotChocolate.FTUE
Interface
Failed |
A property to be set by the IFtueSteps. The FtueEvent can be triggered again if this returns true. |
Description
The cumulated result of FtueEvents.
Tip
Use the IFtueResult to record the player's choices and give rewards!
Namespace: HotChocolate.FTUE
Interface
Info |
A string property to help with debugging. |
Execute |
The task to be executed. |
Description
If for some reason you want to write your own FtueStep, it must implement IFtueStep.
Namespace: HotChocolate.FTUE; Inherits from: IFtueStep
Properties
Info |
A string for debugging purposes. |
Methods
Execute |
The method that executes this step. Calls _Execute. |
_Execute |
The implementation of Execute by derived classes. |
Description
FtueStep is the class you want to derive from to create your own game specific steps.
Usage
using HotChocolate.FTUE;
using HotChocolate.FTUE.Widgets;
using HotChocolate.Samples.UI;
using Newtonsoft.Json.Linq;
using System;
using System.Threading;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.AddressableAssets;
namespace HotChocolate.Samples.FTUE.Steps
{
public class ShowDialogue : FtueStep, IDialogue
{
public string dialogueKey;
public DialogueBubbleAnchor dialogueBubbleAnchor;
public DialogueCharacterAnchor dialogueCharacterAnchor;
public bool dontPopDialogueBox;
public string hintConfigAddress;
public string Dialogue => dialogueKey; //localize me
public string CharacterName => Config.characterNameKey; //localize me
public Sprite CharacterSprite => Config.characterSprite;
public DialogueBubbleAnchor DialogueBubbleAnchor => dialogueBubbleAnchor;
public DialogueCharacterAnchor DialogueCharacterAnchor => dialogueCharacterAnchor;
public bool DontPopDialogueBox => dontPopDialogueBox;
public TutorialHintConfig Config { get; private set; }
protected override async Task<IFtueResult> _Execute(IFtueResult result, object data, IFtueListener listener, CancellationToken ct)
{
using (new UIRoot.BlockInputScope(FtueEvent.Data(data).UiRoot))
{
Config = await Addressables.LoadAssetAsync<TutorialHintConfig>(hintConfigAddress).Task;
}
if (!ct.IsCancellationRequested)
{
var ftueElement = listener.GetElementToActivate(this);
if (ftueElement != null)
{
await ftueElement.ActivateFtue(this, ct);
}
}
return result;
}
}
}
public async Task<IFtueResult> Execute(IFtueResult currentResult, object data, IFtueListener listener, CancellationToken ct)
Parameters
Description
Calls the abstract method _Execute that has exactly the same signature.
Namespace: HotChocolate.FTUE; Inherits from: FtueStep
Properties
Description
Implements the Execute method to execute a series of IFtueSteps.
Namespace: HotChocolate.FTUE
Interface
OnBecameTrue |
An event that fires anytime Refresh is called and the condition is true. |
Init |
A method to be called before use. Takes an instance of TData. |
IsTrue |
The method to evaluate the condition. |
Refresh |
Reevaluates the condition. Triggers OnBecameTrue if condition became true. |
Dispose |
Cleanup. |
Description
If for some reason you want to write your own FtueCondition, it must implement IFtueCondition.
Namespace: HotChocolate.FTUE; Inherits from: IFtueCondition
Properties
OnBecameTrue |
An event that fires anytime Refresh is called and the condition is true. |
invert |
Inverts the result of IsTrue. |
alwaysTrigger |
Will trigger OnBecameTrue every time Refresh is called and condition is true regardless of its previous state. |
data |
The custom object passed on Init. |
listener |
The IFtueListener passed on Init. |
Methods
Init |
Initializes the condition with the given data object. Calls _Init. |
IsTrue |
The method to evaluate the condition. Calls _IsTrue. |
Refresh |
A method to be called by the derived class anytime the state of the condition may have changed. |
Dispose |
Called by FtueEvent when the condition is not longer needed. |
_Init |
The implementation of Init by derived classes. |
_IsTrue |
The implementation of IsTrue by derived classes. |
_Dispose |
The implementation of Dispose by derived classes. |
Description
FtueCondition is the class you want to derive from to create your own game specific conditions.
Usage
using HotChocolate.FTUE;
using Newtonsoft.Json.Linq;
namespace HotChocolate.Samples.FTUE.Conditions
{
public class CurrentSceneIs : FtueCondition
{
public string sceneName;
protected override void _Init()
{
FtueEvent.Data(data).SceneStack.OnScenePushed += OnScenePushed;
FtueEvent.Data(data).SceneStack.OnScenePopped += OnScenePopped;
}
protected override void _Dispose()
{
FtueEvent.Data(data).SceneStack.OnScenePushed -= OnScenePushed;
FtueEvent.Data(data).SceneStack.OnScenePopped -= OnScenePopped;
}
private void OnScenePushed(World.ISceneData instance)
{
Refresh();
}
private void OnScenePopped(World.ISceneData instance)
{
Refresh();
}
protected override bool _IsTrue()
{
return FtueEvent.Data(data).SceneStack.Top != null && FtueEvent.Data(data).SceneStack.Top.SceneDef.SceneName == sceneName;
}
}
}
Namespace: HotChocolate.FTUE; Inherits from: FtueCondition
Properties
Description
Evaluates a group of IFtueConditions.
Enum
Namespace: HotChocolate.FTUE
Interface
ShouldActivateFtue |
Returns true if this element should be the one to be activated during this IFtueStep. Is called by FtueListener. |
ActivateFtue |
The task to execute when the element is activated by a IFtueStep. |
Description
IFtueElements are registered in the FtueListener and are meant to be activated by certain IFtueSteps.
Namespace: HotChocolate.FTUE.Widgets; Inherits from: MonoBehaviour, IFtueElement
Generics
TData |
An object that will be passed to the findMenuRoot and recenterCamera delegates. Defines the type of IFtueStep to use. |
TResult |
The object to be returned as the result of an FtueEvent. Must implement IFtueResult. Defines the type of IFtueStep to use. |
Properties
blocker |
An object that will block all inputs under the tutorial. |
tutorialPanel |
The root of the whole tutorial UI. |
pointerWorldRect |
A RectTransform that will fit the dimensions of a 3D element. |
hintBoxAnchor |
The RectTransform to use as parent when instantiating a TutorialHintBox. |
dialogueBoxAnchor |
The RectTransform to use as parent when instantiating a TutorialDialogueBox. |
pointerAnchor |
The RectTransform to use as parent when instantiating a TutorialPointer. |
continueButton |
A fullscreen button used for tap anywhere and world hint tutorials. |
mask |
A SoftMask to highlight the current element. Optional. |
getCamera |
A delegate that is used to retrieve the current camera. Is set by the Init method. |
recenterCamera |
A delegate that is used to recenter the camera on an object. Is set by the Init method. |
findMenuRoot |
A delegate that is used to find the root transform of a menu scope. Is passed to the Init method. |
Methods
Description
A UI Canvas that will display tutorial arrows, tutorial hint boxes and tutorial dialogue boxes on IFtueSteps that implement IMenuHint, IWorldHint or IDialogue.
Usage
using System.Threading.Tasks;
using UnityEngine;
namespace HotChocolate.Samples.FTUE
{
public class TutorialView : TutorialView<NavigationController, FtueResult>
{
public static Camera GetCamera(NavigationController nav)
{
return nav.Camera;
}
public static async Task RecenterCamera(IWorldHint worldHint, NavigationController nav, CancellationToken ct)
{
float zoom = worldHint.CameraHeight == -1 ? nav.Camera.transform.position.y - nav.TopViewCamera.Ground.y : worldHint.CameraHeight;
await nav.RecenterCamera(worldHint.Position, zoom, worldHint.RecenterDuration, ct);
}
public static Transform FindMenuRoot(IMenuHint menuHint, NavigationController nav)
{
switch (menuHint.SearchScope)
{
case MenuHintScope.Menu: return nav.UiRoot.menuStack.transform;
case MenuHintScope.Popup: return nav.UiRoot.popupStack.transform;
case MenuHintScope.World: return nav.UiRoot.worldCollider.transform;
}
return nav.UiRoot.transform;
}
}
}
//at startup
var tutorialView = Instantiate(tutorialViewPrefab);
tutorialView.Init(nav, ftueListener, TutorialView.GetCamera, TutorialView.RecenterCamera, TutorialView.FindMenuRoot);
Namespace: HotChocolate.FTUE.Widgets; Inherits from: MonoBehaviour
Properties
blockers |
A bunch of transparent images that will block inputs outside of the target RectTransform. |
handAnchor |
A RectTransform that will rotate according to the anchor type. |
maskRect |
A RectTransform that will be used by the TutorialView to apply a mask around the highlighted element. |
Methods
Init |
Must be called before use. Sets the current RectTransform target, camera and anchor type. Camera should be null for Canvas in overlay mode. Set allowInputOutsideTarget to disable the blockers. |
UpdatePosition |
After Init, call this every frame or whenever the target changes. |
Description
A widget used to highlight a RectTransform. It's usually an arrow or hand pointer. It can also be just an inverted mask.
Namespace: HotChocolate.FTUE.Widgets; Inherits from: MonoBehaviour
Properties
bubbleBg |
The different bubble GameObjects tied to the anchor types. |
message |
The text component to set the localized message. |
panelAnchor |
The whole hint box panel. |
Methods
Init |
Must be called before use. Sets the current RectTransform target, camera, anchor type and message. Camera should be null for Canvas in overlay mode. |
UpdatePosition |
After Init, call this every frame or whenever the target changes. |
Description
A widget used to display a text bubble next to a RectTransform.
Enum
Top |
Bottom |
Left |
Right |
Center |
Namespace: HotChocolate.FTUE.Widgets; Inherits from: MonoBehaviour
Properties
Methods
Description
A widget used to display a character image and a dialogue box.
Enum
Enum
Namespace: HotChocolate.FTUE.Widgets
Interface
Dialogue |
The localized text to show in a TutorialDialogueBox. If null or empty, the dialogue box will not appear in the TutorialView. |
CharacterName |
The localized name of the character in a TutorialDialogueBox. Optional. |
CharacterSprite |
The sprite override of the character in a TutorialDialogueBox. Optional. |
Hint |
The localized text to show in a TutorialHintBox. If null or empty, the hint box will not appear in the TutorialView. |
TagId |
The id of the FtueTag we want to find. |
SearchScope |
Determines the root object to start searching into. |
CustomSearchScope |
A custom value meant to be used with SearchScope.Custom. Optional. |
SearchTimeout |
The time in seconds after which we give up searching for ElementName. |
Completion |
TapAnywhere or PressButton. PressButton will search for a Button in the children of the element and wait for the user to press it. |
PointerAnchor |
The anchor type of the TutorialPointer. |
HintBoxAnchor |
The anchor type of the TutorialHintBox. |
DialogueBubbleAnchor |
The bubble anchor type of the TutorialDialogueBox. |
DialogueCharacterAnchor |
The character anchor type of the TutorialDialogueBox. |
IncludeInactive |
Will include inactive game objects in search. |
SkipIfInactive |
Will skip the tutorial step if the element found is inactive. |
HighlightElement |
Will search for a IHighlightable in the element's children and highlight it. |
DontPopDialogueBox |
The dialogue box will stay active when this step is over. |
Config |
The TutorialHintConfig file to use. |
Description
The interface to implement in order to make a IFtueStep into a menu highlight step usable by the TutorialView.
Usage
using HotChocolate.FTUE;
using HotChocolate.FTUE.Widgets;
using HotChocolate.Samples.UI;
using Newtonsoft.Json.Linq;
using System;
using System.Threading;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.AddressableAssets;
namespace HotChocolate.Samples.FTUE.Steps
{
public class ShowMenuHint : FtueStep, IMenuHint
{
public string tagId;
public MenuHintScope searchScope;
public string searchParent;
public float searchTimeout = 5f;
public MenuHintCompletion completion;
public string hintKey;
public string dialogueKey;
public TutorialWidgetAnchor pointerAnchor;
public TutorialWidgetAnchor hintBoxAnchor;
public DialogueBubbleAnchor dialogueBubbleAnchor;
public DialogueCharacterAnchor dialogueCharacterAnchor;
public bool includeInactive;
public bool skipIfInactive;
public bool highlightElement;
public bool dontPopDialogueBox;
public string hintConfigAddress;
public string Dialogue => dialogueKey; //localize me
public string CharacterName => Config.characterNameKey; //localize me
public Sprite CharacterSprite => Config.characterSprite;
public string Hint => hintKey; //localize me
public string TagId => tagId;
public MenuHintScope SearchScope => searchScope;
public int CustomSearchScope => -1;
public string SearchParent => searchParent;
public float SearchTimeout => searchTimeout;
public MenuHintCompletion Completion => completion;
public TutorialWidgetAnchor PointerAnchor => pointerAnchor;
public TutorialWidgetAnchor HintBoxAnchor => hintBoxAnchor;
public DialogueBubbleAnchor DialogueBubbleAnchor => dialogueBubbleAnchor;
public DialogueCharacterAnchor DialogueCharacterAnchor => dialogueCharacterAnchor;
public bool IncludeInactive => includeInactive;
public bool SkipIfInactive => skipIfInactive;
public bool HighlightElement => highlightElement;
public bool DontPopDialogueBox => dontPopDialogueBox;
public TutorialHintConfig Config { get; private set; }
protected override async Task<IFtueResult> _Execute(IFtueResult result, object data, IFtueListener listener, CancellationToken ct)
{
using (new UIRoot.BlockInputScope(FtueEvent.Data(data).UiRoot))
{
Config = await Addressables.LoadAssetAsync<TutorialHintConfig>(hintConfigAddress).Task;
}
if (!ct.IsCancellationRequested)
{
var ftueElement = listener.GetElementToActivate(this);
if (ftueElement != null)
{
await ftueElement.ActivateFtue(this, ct);
}
}
return result;
}
}
}
Enum
Menu |
Popup |
World |
All |
Custom |
Enum
Namespace: HotChocolate.FTUE.Widgets; Inherits from: MonoBehaviour
Properties
id |
A string that identifies this tag. |
Description
FtueTags are meant to be put on UI elements so they can be found by a IMenuHint ftue step.
Namespace: HotChocolate.FTUE.Widgets
Interface
Dialogue |
The localized text to show in a TutorialDialogueBox. If null or empty, the dialogue box will not appear in the TutorialView. |
CharacterName |
The localized name of the character in a TutorialDialogueBox. Optional. |
CharacterSprite |
The sprite override of the character in a TutorialDialogueBox. Optional. |
Hint |
The localized text to show in a TutorialHintBox. If null or empty, the hint box will not appear in the TutorialView. |
Position |
The position in world space of the 3D object to highlight. |
Radius |
The radius of the 3D object to highlight if Collider is null. |
CameraHeight |
The desired height of the camera relative to the 3d object. |
Collider |
The Collider component of the 3D object to highlight. |
Highlightable |
An IHighlightable object to highlight. Optional. |
Completion |
TapOnObject, TapAnywhere or WaitForCancel. TapOnObject and TapAnywhere will actually wait for a button press. WaitForCancel will only complete when cancellation is requested on the CancellationToken of the IFtueStep. |
PointerAnchor |
The anchor type of the TutorialPointer. |
HintBoxAnchor |
The anchor type of the TutorialHintBox. |
DialogueBubbleAnchor |
The bubble anchor type of the TutorialDialogueBox. |
DialogueCharacterAnchor |
The character anchor type of the TutorialDialogueBox. |
RecenterCamera |
Should the camera transition to center on the object. |
RecenterDuration |
The duration in seconds for recentering the camera. |
DontPopDialogueBox |
The dialogue box will stay active when this step is over. |
Config |
The TutorialHintConfig file to use. |
Description
The interface to implement in order to make a IFtueStep into a 3D object highlight step usable by the TutorialView.
Usage
using HotChocolate.FTUE;
using HotChocolate.FTUE.Widgets;
using HotChocolate.Samples.UI;
using Newtonsoft.Json.Linq;
using System;
using System.Threading;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.AddressableAssets;
namespace HotChocolate.Samples.FTUE.Steps
{
public class ShowBuildingHint : FtueStep, IWorldHint
{
public string buildingId;
public WorldHintCompletion completion;
public string hintKey;
public string dialogueKey;
public TutorialWidgetAnchor pointerAnchor;
public TutorialWidgetAnchor hintBoxAnchor;
public DialogueBubbleAnchor dialogueBubbleAnchor;
public DialogueCharacterAnchor dialogueCharacterAnchor;
public float cameraHeight = -1;
public bool recenterCamera = true;
public float recenterDuration = 1f;
public bool dontPopDialogueBox;
public string hintConfigAddress;
public string Dialogue => dialogueKey; //localize me
public string CharacterName => Config.characterNameKey; //localize me
public Sprite CharacterSprite => Config.characterSprite;
public string Hint => hintKey; //localize me
public Vector3 Position => Building?.transform.position ?? Vector3.zero;
public float Radius => Collider?.bounds.extents.x ?? 0.5f;
public float CameraHeight => cameraHeight;
public Collider Collider => Building?.GetComponentInChildren<Collider>();
public IHighlightable Highlightable => null;
public WorldHintCompletion Completion => completion;
public TutorialWidgetAnchor PointerAnchor => pointerAnchor;
public TutorialWidgetAnchor HintBoxAnchor => hintBoxAnchor;
public DialogueBubbleAnchor DialogueBubbleAnchor => dialogueBubbleAnchor;
public DialogueCharacterAnchor DialogueCharacterAnchor => dialogueCharacterAnchor;
public bool RecenterCamera => recenterCamera;
public float RecenterDuration => recenterDuration;
public bool DontPopDialogueBox => dontPopDialogueBox;
public TutorialHintConfig Config { get; private set; }
public Building Building { get; private set; }
protected override async Task<IFtueResult> _Execute(IFtueResult result, object data, IFtueListener listener, CancellationToken ct)
{
using (new UIRoot.BlockInputScope(FtueEvent.Data(data).UiRoot))
{
Config = await Addressables.LoadAssetAsync<TutorialHintConfig>(hintConfigAddress).Task;
}
var buildings = World.Utils.FindAllInScene<Building>(FtueEvent.Data(data).SceneStack.Top.Scene);
Building = buildings.Find(b => b.id == buildingId);
if(Building != null && !ct.IsCancellationRequested)
{
var ftueElement = listener.GetElementToActivate(this);
if (ftueElement != null)
{
await ftueElement.ActivateFtue(this, ct);
}
}
return result;
}
}
}
Enum
TapOnObject |
TapAnywhere |
WaitForCancel |
Namespace: HotChocolate.FTUE.Widgets
Interface
Description
The interface to implement to display a simple TutorialDialogueBox.
Usage
using HotChocolate.FTUE;
using HotChocolate.FTUE.Widgets;
using HotChocolate.Samples.UI;
using Newtonsoft.Json.Linq;
using System;
using System.Threading;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.AddressableAssets;
namespace HotChocolate.Samples.FTUE.Steps
{
public class ShowDialogue : FtueStep, IDialogue
{
public string dialogueKey;
public DialogueBubbleAnchor dialogueBubbleAnchor;
public DialogueCharacterAnchor dialogueCharacterAnchor;
public bool dontPopDialogueBox;
public string hintConfigAddress;
public string Dialogue => dialogueKey; //localize me
public string CharacterName => Config.characterNameKey; //localize me
public Sprite CharacterSprite => Config.characterSprite;
public DialogueBubbleAnchor DialogueBubbleAnchor => dialogueBubbleAnchor;
public DialogueCharacterAnchor DialogueCharacterAnchor => dialogueCharacterAnchor;
public bool DontPopDialogueBox => dontPopDialogueBox;
public TutorialHintConfig Config { get; private set; }
protected override async Task<IFtueResult> _Execute(IFtueResult result, object data, IFtueListener listener, CancellationToken ct)
{
using (new UIRoot.BlockInputScope(FtueEvent.Data(data).UiRoot))
{
Config = await Addressables.LoadAssetAsync<TutorialHintConfig>(hintConfigAddress).Task;
}
if (!ct.IsCancellationRequested)
{
var ftueElement = listener.GetElementToActivate(this);
if (ftueElement != null)
{
await ftueElement.ActivateFtue(this, ct);
}
}
return result;
}
}
}
Namespace: HotChocolate.FTUE.Widgets
Interface
StartHighlight |
A method that is called by TutorialView when the highlight starts. |
StopHighlight |
A method that is called by TutorialView when the highlight stops. |
Description
The interface to implement to create highlight animations on UI elements and 3D elements.
Usage
using HotChocolate.FTUE.Widgets;
using HotChocolate.Motion;
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
namespace HotChocolate.Samples.FTUE
{
[RequireComponent(typeof(Image))]
public class MenuHighlight : MonoBehaviour, IHighlightable
{
public MenuHighlightConfig config;
private Color originalColor;
public void StartHighlight()
{
var image = GetComponent<Image>();
originalColor = image.color;
StartCoroutine(HighlightCoroutine());
}
public void StopHighlight()
{
GetComponent<Image>().color = originalColor;
StopAllCoroutines();
}
private IEnumerator HighlightCoroutine()
{
var sequence = new ClipSequence();
var inAnim = new Tween<Color>(config.loopDuration / 2f, originalColor, config.color, Color.Lerp, Easing.QuadEaseInOut);
inAnim.OnUpdate += UpdateColor;
var outAnim = new Tween<Color>(config.loopDuration / 2f, config.color, originalColor, Color.Lerp, Easing.QuadEaseInOut);
outAnim.OnUpdate += UpdateColor;
sequence.Append(inAnim);
sequence.Append(outAnim);
while(true)
{
if(!sequence.Play(Time.deltaTime))
{
sequence.Seek(0);
}
yield return null;
}
}
private void UpdateColor(Color color, float progress)
{
GetComponent<Image>().color = color;
}
}
}
Namespace: HotChocolate.FTUE.Widgets; Inherits from: ScriptableObject
Properties
Description
The config file used in IMenuHint and IWorldHint steps.
Top View Camera
Namespace: HotChocolate.Cameras;
Properties
Boundaries |
The current Boundaries of the camera. |
Ground |
The current ground position. Default is Vector3.zero. |
Methods
Init |
Must be called before use. Sets the Camera and TopViewCameraConfig. |
Reset |
Resets the current state to default. Call this when the use of the TopViewCamera is discontinued. |
Move |
Call this every frame to move the camera in Pan, Zoom and Rotate. |
Pan |
Call this every frame to Pan the camera. |
Zoom |
Call this every frame to Zoom the camera. |
Rotate |
Call this every frame to Rotate the camera. |
IsInBoundaries |
Returns true if the camera is currently in the Boundaries or if Boundaries is null. |
Description
Moves a top view Camera around in Pan, Zoom and Rotate. Also provides a bounce when zooming out of range.
public void Move(float deltaTime, MoveGesture move)
public void Move(float deltaTime, bool touchIsActive, Vector2 deltaPos, float deltaScale, float localScale, float deltaAngle, Vector2 screenPos)
Parameters
deltaTime |
Duration of the frame. |
move |
A MoveGesture to drive the camera. |
touchIsActive |
Is the current touch valid for moving the camera. |
deltaPos |
The delta position in UI local space during this frame. Should include inertia. |
deltaScale |
The delta scale in UI local space during this frame. Should include inertia. |
localScale |
The current scale of the touches in UI local space. |
deltaAngle |
The delta angle during this frame. Should include inertia. |
screenPos |
The current screen position of the touch. |
Description
Moves a top view Camera around in Pan, Zoom and Rotate for one frame. Also provides a bounce when zooming out of range.
Usage
private void Update()
{
if (_move != null)
{
_tap.Update(Time.deltaTime);
_move.Update(Time.deltaTime);
if (_tap.IsTrue)
{
ClickableObject.RaycastAll(_tap.ScreenPos, Camera, new BuildingData() { uiRoot = UiRoot });
}
else
{
TopViewCamera.Move(Time.deltaTime, _move);
}
}
}
Tip
The MoveGesture is a powerful abstraction for moving cameras around since it converts the touches from the player into Pan, Rotate and Scale. It also handles inertia!
public void Pan(bool touchIsActive, Vector2 deltaPos, Vector2 screenPos)
Parameters
touchIsActive |
Is the current touch valid for moving the camera. |
deltaPos |
The delta position in UI local space during this frame. Should include inertia. |
screenPos |
The current screen position of the touch. |
Description
Pans a top view camera for one frame.
public void Zoom(float deltaScale, float localScale, Vector2 screenPos)
Parameters
deltaScale |
The delta scale in UI local space during this frame. Should include inertia. |
localScale |
The current scale of the touches in UI local space. |
screenPos |
The current screen position of the touch. |
Description
Zooms a top view camera for one frame.
public void Rotate(float deltaAngle)
Parameters
deltaAngle |
The delta angle during this frame. Should include inertia. |
Description
Rotates a top view camera for one frame.
Namespace: HotChocolate.Cameras; Inherits from: ScriptableObject
Properties
minZoom |
The shortest height the camera can get from the ground. |
maxZoom |
The farthest height the camera can get from the ground. |
zoomSpeed |
The speed at which the camera will zoom. |
zoomSpeedModifierAtMin |
The speed modifier at min zoom. Zooming speed is logarithmic. |
groundLayerMask |
The name of the layer to raycast the ground. Can be null if ground is 0. |
bounceDuration |
The duration in seconds of the bounce when the camera zooms out of range. |
floorBounceAmount |
The distance of the bounce when min zoom is exceeded. |
ceilingBounceAmount |
The distance of the bounce when max zoom is exceeded. |
obstacleClimbSmoothness |
How smoothly should the camera move from one ground level to another. |
allowRotation |
Should this camera be allowed to rotate. |
allowBounce |
Should this camera be allowed to bounce. |
Description
The configuration asset to be used with TopViewCamera.
Namespace: HotChocolate.Cameras; Inherits from: MonoBehaviour
Properties
limits |
A Rect that defines the boundaries. It is relative to the transform position and is flat on the ground. |
Methods
IsIn |
Returns true if a world position is within the boundaries. Returns false if the world position is on the edge of the boundaries. |
BottomLeft |
Returns the world position of the bottom left limit. |
BottomRight |
Returns the world position of the bottom right limit. |
TopLeft |
Returns the world position of the top left limit. |
TopRight |
Returns the world position of the top right limit. |
Center |
Returns the world position of the center of the limits. |
ClosestPoint |
Returns the closest world position within the limits from a given world position. |
Description
Boundaries is a MonoBehaviour meant to be used as limits for a TopViewCamera.
Motion
The Motion library exists for creating sequences that can be played wherever you want, may it be inside a Unity coroutine, an update loop, a C# task, etc. It can be used to create UI tweens, but also anything you can think of that requires to play a sequence of events, such as cutscenes and even sound effects!
Namespace: HotChocolate.Motion
Interface
Duration |
Returns the total duration of the clip in seconds. |
Play |
A function to be called every frame. Returns false when completed. |
Seek |
Sets the clip to a given time position between 0 and 1. |
Description
A IClip is an object that can be played forward or backwards like a cassette tape. It must be playable from beginning to end. In reverse mode, it must play from end to beginning. It can be put into a ClipSequence and the sequence itself should retain the properties of a IClip.
bool Play(float elapsed, bool reverse)
Parameters
elapsed |
The duration in seconds of the current frame. |
reverse |
Should the IClip be played backwards. |
Description
Must be called every frame to play the IClip. Not calling it should pause the IClip. Returns false when the end of the IClip is reached. Seeking to an earlier time position should allow the IClip to be played again.
void Seek(float progress)
Parameters
progress |
The amount of completion to jump to, described as a value between 0 and 1. |
Description
Sets the time position of the IClip to a given progress value. Should allow the IClip to be played again if value is less than 1.
Namespace: HotChocolate.Motion; Inherits from: IClip
Properties
Duration |
The total duration in seconds of the whole sequence. |
OnFinish |
An event that is called when the sequence is completed. |
Methods
Description
A sequence of IClips that itself has the same properties as a IClip, meaning that a ClipSequence can be appended to a ClipSequence.
Namespace: HotChocolate.Motion; Inherits from: IClip
Generics
T |
The type of object to tween. |
Properties
Duration |
The duration in seconds of the tween. |
OnUpdate |
An event that is invoked every time Play is called while the tween is not finished. It contains the current tween value and the current progress between 0 and 1. |
OnFinish |
An event that is called when the tween is finished. |
Methods
Constructor |
Takes a duration in seconds, a start value, an end value, an interpolation function (example: Vector3.Lerp) and an easing function (see Easing). |
Play |
See IClip.Play. |
Seek |
See IClip.Seek. |
Description
A IClip that uses a tween function.
Usage
private IEnumerator InAnimationCoroutine(FadingPanelConfig config, float delay)
{
GetComponent<CanvasGroup>().alpha = config.inAlphaStart;
var clip = new Motion.ClipSequence();
var inAnimation = new Motion.Tween<float>(config.fadeInDuration, GetComponent<CanvasGroup>().alpha, config.inAlphaEnd, Mathf.Lerp, Motion.EasingUtil.EasingFunction(config.inAnimationEasing));
inAnimation.OnUpdate += UpdateAlpha;
if (config.inDelay + delay > 0)
{
clip.Append(new Motion.Silence(config.inDelay + delay));
}
clip.Append(inAnimation);
while (clip.Play(Time.deltaTime))
{
yield return null;
}
}
private void UpdateAlpha(float value, float progress)
{
GetComponent<CanvasGroup>().alpha = value;
}
Namespace: HotChocolate.Motion; Inherits from: IClip
Properties
Duration |
The duration in seconds of the silence. |
OnFinish |
An event that is called when the clip is completed. |
Methods
Description
A IClip that does nothing for a given duration. Useful for adding delays in ClipSequences.
Namespace: HotChocolate.Motion; Static Class
Description
Regroups all of the known tween functions ("https://easings.net/"). Can be used as easing parameter in Motion.Tween.
Enum
Linear |
ElasticEaseIn |
ElasticEaseOut |
ElasticEaseInOut |
BounceEaseIn |
BounceEaseOut |
BounceEaseInOut |
QuadEaseIn |
QuadEaseOut |
QuadEaseInOut |
BackEaseIn |
BackEaseOut |
BackEaseInOut |
ExpoEaseIn |
ExpoEaseOut |
ExpoEaseInOut |
CircEaseIn |
CircEaseOut |
CircEaseInOut |
QuartEaseIn |
QuartEaseOut |
QuartEaseInOut |
QuintEaseIn |
QuintEaseOut |
QuintEaseInOut |
SineEaseIn |
SineEaseOut |
SineEaseInOut |
EasingFunction EasingFunction(EasingType type)
Parameters
Description
Returns the easing function associated with the given EasingType.
Gestures
The goal of gestures is to abstract touches and mouse clicks into a device agnostic form. In addition to saving you the trouble of caring about the type of input you are dealing with, using gestures also provides a few useful functionalities such as inertia and touch duration.
Namespace: HotChocolate.Gestures
Properties
MinDuration |
The minimum time in seconds for a hold to be true. |
DragTolerance |
The amount of movement in UI local space allowed before a touch is no longer valid for hold. |
MustStayWithinZone |
Should the touch stay within the input zone in order to be valid. |
IsTrue |
Is the hold true. |
IsValid |
Can this hold gesture eventually become true or has it been invalidated. |
LocalPos |
The current touch position in UI local space. First touch only. |
ScreenPos |
The current touch position in screen space. First touch only. |
TouchDuration |
The total duration of the current hold gesture. |
Methods
Constructor |
Takes the RectTransform that is the valid zone for the hold gesture and the camera that is used to render the UI Canvas. The camera should be null if the Canvas is in overlay mode. |
Update |
Must be called every frame to update the hold gesture. Takes the duration of the frame as a parameter. |
Release |
Invalidates the current hold gesture. |
Description
This gesture becomes true after a touch or click has been down for a given duration. It is only valid if there is exactly one touch.
Namespace: HotChocolate.Gestures
Properties
MaxForce |
Expresses how much the resulting delta lags behind the actual touch. A MaxForce of 1 means no lag, 0 means no movement. |
Friction |
Expresses the speed at which the resulting delta will stop moving after touch release. A Friction of 1 means immediate stopping, 0 means no stopping at all. |
AllowMoveWithTwoFingers |
Is the pan valid when two touches or more are down. |
MouseWheelScaleSpeed |
A fudge factor to convert the touch scale on device (zoom with two fingers) into the mouse wheel scale. |
MouseRotationSpeed |
A multiplier for rotation speed with the mouse. |
IsActive |
Is the move gesture currently valid and there is at least one touch. |
LocalPos |
The current touch position in UI local space. If there is two touches, it is the average position of the two. The third touch is ignored. |
ScreenPos |
The current touch position in screen space. If there is two touches, it is the average position of the two. The third touch is ignored. |
DeltaPos |
The difference between the current LocalPos and the previous one. |
LocalScale |
The current distance between two touches in UI local space. On PC it is always 0. |
DeltaScale |
The difference between the current LocalScale and the previous one. With the mouse it uses the current wheel delta multiplied by the MouseWheelScaleSpeed. |
LocalAngle |
The current angle in degrees between two touches. On PC it is the cumulation of all previous DeltaAngles. |
DeltaAngle |
The difference between the current LocalAngle and the previous one. On PC, rotation is achieved with a drag movement while the Alt key is held. |
TwoFingers |
Indicates whether two or more touches are present. On PC, it means the Alt key is held. |
Methods
Constructor |
Takes the RectTransform that is the valid zone for the move gesture and the camera that is used to render the UI Canvas. The camera should be null if the Canvas is in overlay mode. |
Update |
Must be called every frame to update the move gesture. Takes the duration of the frame as a parameter. |
Reset |
Resets and invalidates the current move gesture. |
Description
This gesture becomes active when a touch or click is made in the input zone and remains active while the touch is down, even if it leaves the zone.
Usage
private MoveGesture _move;
private TapGesture _tap;
private void Update()
{
if (_move != null)
{
_tap.Update(Time.deltaTime);
_move.Update(Time.deltaTime);
if (_tap.IsTrue)
{
ClickableObject.RaycastAll(_tap.ScreenPos, Camera, new BuildingData() { uiRoot = UiRoot });
}
else
{
TopViewCamera.Move(Time.deltaTime, _move);
}
}
}
Namespace: HotChocolate.Gestures
Properties
MaxDuration |
Time in seconds after which a touch is no longer valid for tap. |
DragTolerance |
The amount of movement in local space allowed before a touch is no longer valid for tap. |
MustStayWithinZone |
Should the touch stay within the input zone in order to be valid. |
IsTrue |
Is the tap true. |
LocalPos |
The current touch position in UI local space. First touch only. |
ScreenPos |
The current touch position in screen space. First touch only. |
Methods
Constructor |
Takes the RectTransform that is the valid zone for the tap gesture and the camera that is used to render the UI Canvas. The camera should be null if the Canvas is in overlay mode. |
Update |
Must be called every frame to update the tap gesture. Takes the duration of the frame as a parameter. |
Description
This gesture becomes true when a touch or click is released within a given maximum duration. It is only valid if there is exactly one touch.
Namespace: HotChocolate.Gestures
Properties
Phase |
The current phase of the touch or click. Up means no touch, Began is true on the first frame of a touch, Down means the touch is held, Ended is true on the frame where the touch is released. |
LocalPos |
The current touch position in UI local space. First touch only. |
ScreenPos |
The current touch position in screen space. First touch only. |
Methods
Constructor |
Takes the RectTransform that is the valid zone for the touch gesture and the camera that is used to render the UI Canvas. The camera should be null if the Canvas is in overlay mode. |
Update |
Must be called every frame to update the touch gesture. |
Description
This is the simplest gesture. It is merely an abstraction of the device touches and PC mouse. It is only valid if there is exactly one touch.
Cheats
Cheats use C# attributes to expose methods and parameters to UI widgets. Cheats are defined in ScriptableObjects.
Usage
[CreateAssetMenu(fileName = "CheatTest", menuName = "HotChocolate/Cheats/Cheat Test", order = 1)]
public class CheatTest : ScriptableObject
{
public float someFloat = 50f;
[Range(0, 1)]
public float someFloatWithRange = 0.5f;
public int someInt = 100;
public int someIndex = 0;
[Range(1, 100)]
public int someIntWithRange = 50;
public string someString = "patate";
public enum SomeEnumType
{
Value1,
Value2,
Value3
}
public SomeEnumType someEnum = SomeEnumType.Value1;
public bool someToggle = false;
[CheatProperty]
public float SomeFloat
{
get { return someFloat; }
set { someFloat = value; }
}
[CheatProperty(MinValue = 0, MaxValue = 1)]
public float SomeFloatWithRange
{
get { return someFloatWithRange; }
set { someFloatWithRange = value; }
}
[CheatProperty]
public int SomeInt
{
get { return someInt; }
set { someInt = value; }
}
[CheatProperty(MinValue = 1, MaxValue = 100)]
public int SomeIntWithRange
{
get { return someIntWithRange; }
set { someIntWithRange = value; }
}
[CheatProperty]
public string SomeString
{
get { return someString; }
set { someString = value; }
}
[CheatProperty]
public SomeEnumType SomeEnum
{
get { return someEnum; }
set { someEnum = value; }
}
[CheatProperty]
public bool SomeToggle
{
get { return someToggle; }
set { someToggle = value; }
}
[CheatMethod]
public void SomeMethod()
{
Debug.Log("Invoking SomeMethod");
}
}
Tip
See See Assets->Cheats in the Sample Project for a usage example!.