Skip to content

Instantly share code, notes, and snippets.

@exts
Created April 28, 2019 14:11
Show Gist options
  • Save exts/4fac3c5606d7b57fc402a3e06e433d33 to your computer and use it in GitHub Desktop.
Save exts/4fac3c5606d7b57fc402a3e06e433d33 to your computer and use it in GitHub Desktop.
using Godot;
namespace Gamma.Core
{
public class Autoload : Node
{
private Node _scene;
public override void _Ready()
{
_scene = Game.CurrentScene();
}
public override void _Notification(int what)
{
if (what == MainLoop.NotificationWmQuitRequest)
Quit();
}
public void Quit()
{
GetTree().Quit(); // default behavior
}
public void SwitchScene(string path)
{
CallDeferred(nameof(SwitchSceneCallback), path);
}
public void SwitchSceneCallback(string path)
{
_scene.Free();
_scene = GD.Load<PackedScene>(path).Instance();
Game.Root().AddChild(_scene);
GetTree().SetCurrentScene(_scene);
}
}
}
using Godot;
namespace Gamma.Core
{
public class Game
{
public static Game Instance => _instance ?? (_instance = new Game());
private static Game _instance;
private bool _initiated;
private Viewport _root;
private Game()
{
Init();
}
public void Init()
{
if(_initiated) return;
_initiated = true;
_root = ((SceneTree) Engine.GetMainLoop()).GetRoot();
}
public static Viewport Root()
{
return Instance._root;
}
public static Node CurrentScene()
{
var root = Root();
return root?.GetChild(root.GetChildCount() - 1);
}
public static Autoload Autoload()
{
return Root().GetNode<Autoload>("Autoload");
}
public static void ExitGame()
{
Autoload().Quit();
}
}
}
using System;
using System.Collections.Generic;
using Gamma.Core.Scripts;
namespace Gamma.Core
{
public enum Scenes
{
MainMenu,
Options,
Credits,
}
public class SceneSwitcher
{
private static readonly Dictionary<Scenes, string> ScenesDict = new Dictionary<Scenes, string>
{
{Scenes.MainMenu, "MainMenu"},
{Scenes.Options, ""},
{Scenes.Credits, "Credits"},
};
public static void Switch(Scenes scene)
{
if(!ScenesDict.ContainsKey(scene))
{
throw new Exception($"Invalid scene you are trying to switch to: {scene}");
}
Game.Autoload().SwitchScene($"res://Data/Scenes/{ScenesDict[scene]}.tscn");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment