LoginSignup
0
1

More than 3 years have passed since last update.

Unity:オブジェクトの表示・非表示のエラー

Posted at

事象

GameOverメッセージを隠しておいて、ゲームオーバーになった時に表示したかったが、表示できなかった。

内容

まず、以下のコードをGameOverテキストを貼り付けたパネルにアタッチしたが、start()の非表示処理は動くのに、update()の表示処理が動かなかった

public class gameStateManager : MonoBehaviour
{

    public static bool gameState = true;

    void Start()
    {
        this.gameObject.SetActive(false);
    }

    void Update()
    {
        Debug.Log("test");

        if (gameState==false)
        {
            this.gameObject.SetActive(true);
        }
    }
}

デバッグ用にログを見たが、ログも出力されていない状態

原因

GameOverを表示するパネルが以下のスクリプトで非活性になり、update()が以後行われなくなっていることが原因だった。

    void Start()
    {
        this.gameObject.SetActive(false);
    }

例えば、数秒後に消えるオブジェクトなどはそれ自身が完全にメモリ上から消える必要があるので、this.gameObject.SetActive(false);で削除して良いが、今回のように表示、非表示を繰り返したい場合は、自身を削除するという処理をするとその後のupdate()が効かなくなる

対処

以下のコードをMainCameraにアタッチして表示非表示の切り替えをすることにした

public class gameStateManager : MonoBehaviour
{

    public static bool gameState = true;
    public string gameOverObject = "GameOverPanel";
    GameObject gameObject;

    void Start()
    {
        gameObject = GameObject.Find(gameOverObject);
        gameObject.SetActive(false);
    }

    void Update()
    {

        if (gameState==false)
        {
            gameObject.SetActive(true);
        }
    }
}
0
1
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
0
1