Infinity PBR by Magic Pig Games
  • Infinity PBR Documentation
  • Game Modules 4
    • ➡️Quick Start
    • 📽️Video Tutorials
      • Quick Start: Creating Game Module Objects
      • Automating Start Actions on GameModulesActor
      • Inflicting Damage with Conditions
      • Updating UI (and more) with Blackboard Notes
      • Dynamic Menus with Item Objects and Dictionaries
      • Create Custom Quest Rewards
      • Save and Load Game Data
      • Stats: Deep Dive
      • Items: Deep Dive
      • Conditions: Deep Dive
      • First Person Movement
      • Tutorial: "Overheal" Effect with Condition & Stats
      • Tutorial: Create a Character & Actor Class Inheriting from GameModulesActor
    • 👀Game Modules Viewer
      • Viewer: Dictionaries
      • Viewer: Stat / GameStatList
      • Viewer: ItemObject / GameItemObjectList
      • Viewer: ItemAttribute / GameItemAttributeList
      • Viewer: Condition / GameConditionList
      • Viewer: Quest / GameQuestList
    • V4 Migration Tips
      • Introducing GameModulesActor
      • Interfaces
      • No More Tick*
      • Dictionaries
      • Repositories
      • Tips from Upgrading "Legend of the Stones"
    • Important Information
      • Game Modules Overview
      • Inherit from GameModulesActor
      • Things to not forget to do
      • Bugs, Backups, and Demos
      • FAQ / Tips & Tricks
      • Required Prefabs
      • Game Module Repository
      • Release Notes
    • Module Documentation
      • Game Modules Actor
      • Game Module "Lists"
        • Get() Methods
          • GameStatList Get() Methods
          • GameItemObjectList Get() Methods
          • GameItemAttribute Get() Methods
          • GameConditionList Get() Methods
          • GameQuestList Get() Methods
        • Contains() Methods
          • GameStatList Contains() Methods
          • GameItemObjectList Contains() Methods
          • GameItemAttributeList Contains() Methods
          • GameConditionList Contains() Methods
          • GameQuestList Contains() Methods
        • Count() Methods
          • GameStatList Count() Methods
          • GameItemObjectList Count() Methods
          • GameItemAttributeList Count() Methods
          • GameConditionList Count() Methods
          • GameQuestList Count() Methods
        • Remove() Methods
          • GameStatList Remove() Methods
          • GameItemObjectList Remove() Methods
          • GameItemAttributeList Remove() Methods
          • GameConditionList Remove() Methods
          • GameQuestList Remove() Methods
        • GameStatList
        • GameItemObjectList
        • GameItemAttributeList
        • GameQuestList
        • GameConditionList
      • Blackboard
        • Blackboard.cs
        • Blackboard Follower
        • Blackboard Note
        • Blackboard Event
        • Blackboard Values
        • Tips & Tricks
          • Use extension methods to check BlackboardNotes (or events)
      • Stats
        • IHaveStats
        • Stat.cs
        • GameStat.cs
        • GameStatList.cs
        • Mastery Levels
      • Loot
        • LootItems.cs
        • LootBox.cs
        • GameLootBox.cs
        • Generating & Handling Loot
        • Custom Loot Generation Algorithm
      • Items
        • ItemObject.cs
          • Manage Item Objects
          • Allowed Item Attributes
          • Starting Item Attributes
          • Item Attribute Variables
            • Variables Methods
        • GameItemObject.cs
        • GameItemObjectList.cs
        • ItemAttribute.cs
          • Manage Item Attributes
          • General Settings
          • Name Settings
          • Requisite Attributes
        • GameItemAttribute.cs
        • GameItemAttributeList.cs
        • Code Examples
      • Conditions
        • Condition.cs
          • Main Settings
          • Condition Time
          • Effects on Points
        • GameCondition.cs
        • GameConditionList.cs
        • Expiration Condition Handler
        • Code Examples
      • Quests
        • Quest
          • Main Settings
          • Quest Step Settings
        • Quest Steps
        • Quest Conditions
          • Create a Custom Quest Condition
            • Your Quest Condition
            • Your Quest Condition Editor
            • Your Quest Condition Drawer
          • Quest Condition Details
            • Blackboard Value Bool
            • Blackboard Value GameObject
            • Blackboard Value Number
            • Blackboard Value String
            • Final Stat Is
            • Game Condition List Contains
            • Game Item Object List Contains
            • Game Stat List Contains
          • Quest Condition Enums
        • Quest Rewards
          • Create a Custom Quest Reward
            • Your Quest Reward
            • Your Quest Reward Editor
            • Your Quest Reward Drawer
          • Quest Reward Details
            • Point Reward
            • Condition Reward
            • Quest Quest Reward
            • Item Object Reward
          • Custom Quest Reward Handler
        • GameQuest
        • GameQuestList
        • Quest Events
        • Demo Scene Quests
          • Push the Button
          • Add Money
          • Don't Get Poisoned
          • Rescue the Puppy
      • Voices
        • Voices
        • Voice.cs
        • Code Examples
      • Dictionaries
        • Dictionaries Setup
        • Dictionaries Methods
        • KeyValue Methods
        • Save and Load
        • Object Reference
      • Gametime & Timeboard
        • Timeboard
          • Timeboard Events
          • TimeboardFollower
        • Gametime
          • Pause Level
          • Time Options
          • Properties & Methods
        • TimeSpan
        • Code Examples
      • Property Code
      • Lookup Table
      • Save and Load
        • GameList & GameFile
        • Making objects saveable
        • Saving, and Loading
        • BlackboardEvents sent by Save and Load
    • Game Module "Systems"
      • Drag-and-Drop Inventory System
        • Scripts
          • PanelManager
          • OnScreenItem
          • Panel
          • BoxManager
        • Scene & Class Setup
        • Item / Object Setup
        • Item / Inventory Setup
        • Box Setup (Chests, Bags, Other Inventories)
        • Setup Your Scene
      • First Person Movement
      • Character Creation
    • Game Module Demo Projects
      • Party Based RPG
        • Title Scene
        • Character Creation Scene
        • World & Dungeon Scenes
    • Magic Time for Game Modules
  • ✨Northstar Tracking System
    • ✅Overview & Quickstart
      • ➡️Quick Start
      • 🫐Demo Scene
      • 🛠️Customizing & Overriding
        • Create a Custom Navigation Bar
        • Create a Custom Compass / Radar
        • Runtime Overrides
          • Screen & Edge Overlay
          • Navigation Bar
          • Compass / Radar
      • ☄️Tips & Code Examples
    • Northstar Documentation
      • Global Northstar Settings
      • Northstar Overlay Settings
      • Compass & Radar
        • Compass
        • Radar
      • Northstar Screen Overlay
        • Screen & Edge Overlay
        • Navigation Bar
      • Tracked Target Compass Radar
      • Tracked Target Overlay
        • Types
        • Override Values
      • Overlay Icon
      • Compass Icon
      • Distance Text
  • 🚀Projectile Factory
    • 👀Overview & Quickstart
      • ➡️Quick Start Guide
        • Create Your First Projectile
        • Add Projectile Factory & Create a Projectile Spawner
        • Use 3rd Party Integrations
        • Extending Projectile Factory
        • Making Lasers & Similar Attached Projectiles
      • 💡FAQs + Important Reminders
    • Game Modules 4 Integration
      • Projectiles with TimeMod
    • Magic Time for Projectile Factory
    • ✅3rd Party Particle Integrations [16]
      • ▶️Archanor VFX [5]
        • Sci-Fi Arsenal
        • Polygon Arsenal
        • Magic Arsenal
        • Retro Arsenal
        • Rainbow Magic
      • ▶️Gabriel Aguiar Prod [2]
        • Unique Projectiles Vol. 1
        • Unique Projectiles Vol. 2
      • ▶️HOVL Studio [4]
        • Toon Projectiles
        • Toon Projectiles 2
        • AAA Stylized Projectiles Vol. 1
        • AAA Projectiles Vol. 2
      • ▶️kripto289 [1]
        • Realistic Effects Pack 4
      • ▶️FORGE3D [1]
        • Sci-Fi Effects
      • ▶️Knife [1]
        • PRO Effects - Sci-Fi Shooter FX
      • ▶️Jean Moreno [1]
        • Cartoon FX Remastered
      • ▶️Synty Studios [1]
        • 🟡Synty Studios Particles
    • Projectile Factory Documentation
      • 🔫Projectile Spawner
        • Projectile Spawner Code
      • 🚀Projectile
        • Projectile Code
        • Projectile Data
      • ✨Spawn Behavior
        • Spawn Behavior Code
        • Spawn Behavior Modification
      • 🕊️Behaviors
        • Behavior Examples
      • ⚡Events
      • 👁️Observers, Global Observers, and Observer Objects
        • Toggle Objects At Events Observer Object
      • 👩‍💼Factory Manager
      • 🏹Trajectory
      • 🎱Object Pooling
      • 🤩Create Custom Behaviors
      • Spawn Point Manager
      • Helper Tools
        • Projectiles Quick Editor
        • Set Trail Auto Destroy to False
        • Set Layer of All Projectiles
        • Remove Colliders
      • Additional Scripts
        • Destroy or Pool Object
        • Project Force
        • Raycast Shooter + Handlers
        • Projectile Utilities
  • Additional Systems & Tools
    • 🎨Runtime Color Sampler
      • Quick Start
      • Demo Walkthrough
      • Runtime Color Sampler (Prefab & Class)
        • Sampler Sphere
        • Sampler Camera
      • Runtime Listener
      • Runtime Color Settings
      • Scripting
      • Additional Classes
    • 🙎‍♀️Portrait Avatars
      • Setup
        • Create a Portrait Avatar
        • Create a UI Portrait
      • Portrait Avatars
        • Scripting
      • Portrait3D
      • Portrait2D
      • Portrait UI
      • Avatar Camera
      • Important Considerations
    • 🎛️Audio Clip Combiner
    • 🌈Color Shifter
    • 🛠️Support Classes
      • Utilities.cs
      • InfinityExtensions.cs
  • ⌛Magic Time - Local Time Scale
    • Overview
    • ➡️Quick Start
    • 🛠️Integrations
    • 💡FAQ
    • Local Time Scale
      • Local Time Scale Scripting
    • Magic Time Manager
      • Magic Time Manager Scripting
    • Magic Time User
      • IHaveLocalTime
      • Magic Time User Scripting
      • Additional "Magic Time User" Components
    • Time Zone
  • Equipment Systems
    • Overview
    • Blend Shapes Manager
    • Blend Shapes Preset Manager
    • Prefab and Object Manager
      • Humanoid Demo & Setup
      • EquipmentObject.cs
      • Prefab Groups
      • Variables
      • Scripting Examples
    • Wardrobe Prefab Manager
  • 📽️General Tutorials
    • Quick 3rd Person Controller
  • ⚔️Legend of the Stones
    • Actors, Players, NPCs
    • Systems
      • Game State
  • External Links
  • Get them at the Asset Store
  • Connect on Discord
  • YouTube
  • Twitch
  • 🚧Work In Progress / Coming Soon
Powered by GitBook
On this page
  • Getting the Time Values
  • Getting & Setting the Value
  • Pausing and Resuming
  • Subscribing
  • Information About Subscribers
  • Unsubscribing
  • Automatically Removing the LocalTimeScale
  • Subscribing to Events

Was this helpful?

  1. Magic Time - Local Time Scale
  2. Local Time Scale

Local Time Scale Scripting

v1.0

PreviousLocal Time ScaleNextMagic Time Manager

Last updated 8 months ago

Was this helpful?

Check the LocalTimeScale class to view all of the methods available.

Getting the Time Values

The LocalTimeScale will have its own time values similar to the Time class. You can get these using DeltaTime, UnscaledDeltaTime, and FixedDeltaTime.

LocalTimeScale localTimeScale;
float _counter = 0f;
float _fixedDeltaTime;

_counter += localTimeScale.DeltaTime;
_fixedCounter += localTimeScale.FixedDeltaTime;

Getting & Setting the Value

The "Value" is a float representing the percent of "real time". 1f is essentially 100% of Time.deltaTime. The Value property will return the current value, and you can also specifically set this value as well using SetValue(float newValue).

If you're using the or interface, often you'll want to know the value of the combined time scales affecting that object. In that case, use the TimeScale property.

// Get the value
LocalTimeScale localTimeScale;
var currentValue = localTimeScale.Value;

// Set the value
float newValue = 0.5f;
localTimeScale.SetValue(newValue);

When the value is changed, the UnityEvent OnTimeScaleChangedUnityEvent and Event OnTimeScaleChanged will be triggered for any subscribers.

If the value is changed to 0f (with or without using the Pause() method), the OnPaused and OnPausedUnityEvent events will be called.

Similarly, if the value changes from 0f to something else, even without using the Resume() method, the OnResumed and OnResumedUnityEvent will be called.

Pausing and Resuming

The Pause() and Resume() methods will set value to 0f, and then return the value to the last cached value. If you know the resumed value should be the same as what it was prior to the "pause" action, then this is often a simpler way of handling this logic. Otherwise, you can always just SetValue(0f) manually.

// Pause this specific localTimeScale
localTimeScale.Pause(); // Will cache the current Value before setting it to 0f.

// Resume this specific localTimeScale
localTimeScale.Resume(); // This will reset to the value when Pause() was called.

Subscribing

Any IHaveLocalTime object can subscribe to a LocalTimeScale object. This will ensure the object gets event notifications from the LocalTimeScale.

Remember, the actual calculations for combined time scale will be handled by the IHaveLocalTime object.

// This is from the "SubscribeToLocalTimeScale(LocalTimeScale myTimeScale)" 
// method on MagicTimeUser.cs

// Can't subscribe to the same timeScale twice.
if (SubscribedTimeScales.Contains(myTimeScale)) return;

SubscribedTimeScales.Add(myTimeScale);
myTimeScale.Subscribe(this);
myTimeScale.OnTimeScaleChanged += OnTimeScaleChanged;

// In this example, we keep track of the timeScales we're subscribed to, and subscribe
// to them at the same time.

When subscribing, the OnSubscribed and OnSubscribedUnityEvent will be called.=

Information About Subscribers

Subscribers are stored in a HashSet<IHaveLocalTime> so there is no index available. There are a few helpful properties that provide more information about subscribers to a specific Local Time Scale.

LocalTimeScale localTimeScale;

// Check the number of subscribers
if (localTimeScale.SubscriberCount == 0)
    return;

// Get the string name of those subscribed
foreach(var subscriberName in localTimeScale.SubscriberNames)
{
    Debug.Log($"{subscriberName} is subscribed");
}

// Get the GameObject of those subscribed
foreach(var subscriberObject in SubscriberGameObjects)
{
    DoSomethingWithSubscriber(subscriberObject);
}

Unsubscribing

You can use the UnsubscribeAll() method to call Unsubscribe() on all current subscribers.

The Unsubscribe(IHaveLocalTime subscriber) method does a few things, if the subscriber passed in is actually subscribed.

First, it will remove the subscriber from the Subscribers list, as you might expect. But it also will call subscriber.UnsubscribeFromLocalTimeScale(this), which allows the subscriber to take any actions as needed.

// This is the method from MagicTimeUser.cs
public virtual void UnsubscribeFromLocalTimeScale(LocalTimeScale timeScale)
{
    if (timeScale == null)
        return;

    // If it is in our list, then unsubscribe and remove it.
    if (SubscribedTimeScales.Contains(timeScale))
    {
        timeScale.Unsubscribe(this);
        SubscribedTimeScales.Remove(timeScale);
    }
            
    // This can be called from the LocalTimeScale, so we may need to reset the desired timeScale, 
    // even if the timeScale is not in our list.
    ResetDesiredTimeScale();
}

Next, the OnUnsubscribed and OnUnsubscribedUnityEvent will be called as well, on the Local Time Scale object. Both of these will pass the subscriber (IHaveLocalTime) object in as a parameter.

Finally, if AutoRemoveWhenEmpty is true, the time scale will be removed. See details below.

Automatically Removing the LocalTimeScale

In some cases, you may wish to automatically remove a LocalTimeScale when there are no subscribers.

localTimeScale.AutoRemoveWhenEmpty = true;

Set AutoRemoveWhenEmpty to true, and then whenever subscribers Unsubscribe() from the Local Time Scale, if there are no subscribers left, then the MagicTimeManager method RemoveTimeScale() method will be called, removing this object.

The check only happens when the Unsubscribe() method is called, so you can safely set this value to true before any subscribers are active.

Subscribing to Events

Classes can subscribe to individual events on the LocalTimeScale class. This is useful to perform actions based on changes to the Local Time Scale.

In the example below, from ZoneColorChanger.cs in the demo, we subscribe and unsubscribe to events on the LocalTimeScale attached to a specific time zone.

In this case, the LocalTimeScale instance is created at runtime, so it will not be availalbe immediately. To handle this, we can subscribe via a Coroutine, which is started OnEnable().

private void OnEnable() => StartCoroutine(SubscribeToTimeScale());

private void OnDisable()
{
    timeZone.TimeScale.OnSubscribed -= OnSubscribed;
    timeZone.TimeScale.OnUnsubscribed -= OnUnsubscribed;
}

private IEnumerator SubscribeToTimeScale()
{
    yield return new WaitUntil(() => timeZone.TimeScale != null);
    timeZone.TimeScale.OnSubscribed += OnSubscribed;
    timeZone.TimeScale.OnUnsubscribed += OnUnsubscribed;
}

// Handle the events -- make sure the object passed is the right type
private void OnSubscribed(object go)
{
    var newObject = (IHaveLocalTime)go;
    if (newObject == null) return;
            
    var newGameObject = newObject.GameObject;
    if (newGameObject == null) return;
            
    AddColor(newGameObject);
}

private void OnUnsubscribed(object go)
{
    var newObject = (IHaveLocalTime)go;
    if (newObject == null) return;
            
    var newGameObject = newObject.GameObject;
    if (newGameObject == null) return;
            
    RemoveColor(newGameObject);
}
⌛
MagicTimeUser
IHaveLocalTime