Skip to content
This repository has been archived by the owner on Oct 19, 2020. It is now read-only.

Static game variables

pixeltris edited this page Jun 6, 2019 · 4 revisions

There are a few different ways of expressing static variables in USharp.

  • Regular static variables which persist between each "Play" session.
  • GameStaticVar<T> variables which are reset on each "Play" session.
  • WorldStaticVar<T> holds a value per world.
  • Variables inside UGameInstance (there is only ever 1 instance of this type per "Play" session).

UGameInstance may be preferred when dealing with UObject instances which may be destroyed when no longer referenced.

Regular static variables

myStaticVar will start at 100 and be increased for each placed actor, every time "Play" is pressed in the editor (it wont reset back to 100 when "Play" is pressed a second time).

[UClass]
class AStaticTest1 : AActor
{
    static int myStaticVar = 100;

    protected override void BeginPlay()
    {
        myStaticVar++;
        PrintString("myStaticVar: " + myStaticVar, FLinearColor.Red);
    }
}

GameStaticVar<T>

myStaticVar will start at 100 and be increased for each placed actor. The value will reset to 100 every time "Play" is pressed in the editor.

[UClass]
class AStaticTest2 : AActor
{
    static GameStaticVar<int> myStaticVar = new GameStaticVar<int>(() => { return 100; });

    protected override void BeginPlay()
    {
        myStaticVar.Value++;
        PrintString("myStaticVar: " + myStaticVar.Value, FLinearColor.Red);
    }
}

UGameInstance

MyVar will start at 100 and be increased for each placed actor. A new UGameInstance will be created every time "Play" is pressed in the editor. UGameInstance is destroyed when the game session ends.

[UClass]
class UStaticTest3GameInstance : UGameInstance
{
    [UProperty]
    public int MyVar { get; set; } = 100;
}

[UClass]
class AStaticTest3 : AActor
{
    protected override void BeginPlay()
    {
        UStaticTest3GameInstance gameInstance = World.GetGameInstance() as UStaticTest3GameInstance;
        if (gameInstance != null)
        {
            myStaticVar.Value++;
            PrintString("MyVar : " + gameInstance.MyVar, FLinearColor.Red);
        }
    }
}
Clone this wiki locally