コガネブログ

平日更新を目標に Unity や C#、Visual Studio、ReSharper などのゲーム開発アレコレを書いていきます

【Unity】開始と終了がある処理を using ステートメントで使用できる「UniScope」を GitHub に公開しました

リポジトリ

使用例

AssetEditingScope

// 通常
AssetDatabase.StartAssetEditing();
//...
AssetDatabase.StopAssetEditing();

// UniScope
using ( new AssetEditingScope() )
{
    //...
}

HandlesColorScope

// 通常
var oldColor = Handles.color;
Handles.color = Color.white;
//...
Handles.color = oldColor;

// UniScope
using ( new HandlesColorScope( Color.white ) )
{
    //...
}

LoadPrefabContentsScope

// 通常
var prefab = PrefabUtility.LoadPrefabContents( "Assets/Cube.prefab" );

prefab.AddComponent<BoxCollider>();

PrefabUtility.SaveAsPrefabAsset( prefab, "Assets/Cube.prefab" );
PrefabUtility.UnloadPrefabContents( prefab );

// UniScope
using ( var scope = new LoadPrefabContentsScope( "Assets/Cube.prefab" ) )
{
    scope.Prefab.AddComponent<BoxCollider>();
    scope.IsSave = true;
}

LogScope

#if ENABLE_RELEASE

// リリースビルドの時はログ出力を無効化
LogScope.OnStart    = null;
LogScope.OnComplete = null;

#else

LogScope.OnStart    = message => Debug.Log( $"{message} 開始" );
LogScope.OnComplete = message => Debug.Log( $"{message} 終了" );

#endif

using ( new LogScope( "ピカチュウ" ) )
{
    Debug.Log( "カイリュー" );
    Debug.Log( "ヤドラン" );
    Debug.Log( "ピジョン" );
}

LockReloadAssembliesScope

// 通常
EditorApplication.LockReloadAssemblies();
//...
EditorApplication.UnlockReloadAssemblies();

// UniScope
using ( new LockReloadAssembliesScope() )
{
    //...
}

SceneSetupScope

// 通常
var oldSetup = EditorSceneManager.GetSceneManagerSetup();
//...
EditorSceneManager.RestoreSceneManagerSetup( oldSetup );

// UniScope
using ( new SceneSetupScope() )
{
    //...
}

CustomSamplerScope

// 通常
var sampler = CustomSampler.Create( "タグ" );
sampler.Begin();
//...
sampler.End();

// UniScope
using ( new CustomSamplerScope( "タグ" ) )
{
    //...
}

GUIColorScope

// 通常
var oldColor = GUI.color;
GUI.color = Color.white;
//...
GUI.color = oldColor;

// UniScope
using ( new GUIColorScope( Color.white ) )
{
    //...
}

LabelWidthScope

// 通常
var oldLabelWidth = EditorGUIUtility.labelWidth;
EditorGUIUtility.labelWidth = 32;
EditorGUILayout.TextField( "Name", "ピカチュウ" );
EditorGUIUtility.labelWidth = oldLabelWidth;

// UniScope
using ( new LabelWidthScope( 32 ) )
{
    EditorGUILayout.TextField( "Name", "ピカチュウ" );
}