LoginSignup
11
6

More than 5 years have passed since last update.

UnityのPlayをせずに関数を呼ぶ

Posted at

はじめに

意外と知らない人がいたので簡単な使い方を。

Unityの再生ボタン(Play)を押さずに関数を呼びたいときありませんか?
例えば保存されているPlayerPrefsのデータを消したりなど。
その時はContextMenuを使うと関数を呼ぶことができます。

公式ドキュメント
https://docs.unity3d.com/ja/2017.4/ScriptReference/ContextMenu.html

ContextMenu 属性はコンテキストメニューにコマンドを追加することができます。
なるほど。わからん
ということで画像で説明してきます。

Script

テストコードを作りました。


public class ContextMenuTest : MonoBehaviour
{

    private string _scoreKey = "Score";

    // Use this for initialization
    void Start ()
    {
        //PlayerPrefsに保存されているUserIdとスコアを取得する.
        var score = PlayerPrefs.GetInt(_scoreKey,0);
        Debug.LogFormat("Score : {0}",score);
    }

    /// <summary>
    /// スコアのセット
    /// </summary>
    /// <param name="score"></param>
    public void SetScore(int score)
    {
        PlayerPrefs.SetInt(_scoreKey,score);
    }

    /// <summary>
    /// 仮のスコアをセットする
    /// </summary>
    [ContextMenu("TestScoreSet")]
    private void TestScoreSet()
    {
        SetScore(100);
    }

    /// <summary>
    /// スコアの値を削除する
    /// </summary>
    [ContextMenu("ClearScore")]
    private void ClearScore()
    {
        PlayerPrefs.DeleteKey(_scoreKey);

    }
}

保存するところは割愛します。
ContextMenuの説明ですが、関数の上に書くと、EditorのComponentの歯車クリックで出るようになります。
[ContextMenu("Editorで表示される名前")]
スクリーンショット (23)_LI.jpg

自分で作った関数をクリックすると実行しなくても関数が呼ばれます。
これの使い所としては、値を削除とかしたい場合にuGUIなどでボタンを作り、実行時にポチっと。。。ということをしなくてもよくなります

ちなみにContextMenuの説明は日本語もできます。
[ContextMenu("スコア削除する")]
スクリーンショット (24).png

これを使ってエンジニア以外の方がUnityを使ってデバッグとか調整とかいろいろやりやすくなればいいなと思いました。

11
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
6