0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Unityのシーン切り替えとStart()組み合わせで悩んだ話

Posted at

初心者が詰まったところを書いてみます.

Unityでシーンを跨いでデータの受け渡しをしたい

ということで,コチラhttps://note.com/suzukijohnp/n/n050aa20a12f1
のnoteの記事を参考にシーンを跨いでデータを引き渡せるようにしました!

終わり!

無理でした

引き渡し値が定数であればこのままで大丈夫です.
でも引き継ぎたいのは変数に入った数でしたので

SceneChanger.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class SceneChanger : MonoBehaviour
{
  private int score;
  public void onClick()
  {
    //スコア引き継ぎ
    SetTakeOverScore();
    // イベントに登録
    SceneManager.sceneLoaded += GameSceneLoaded;

    // シーン切り替え
    SceneManager.LoadScene("GameScene");
  }
  private void GameSceneLoaded(Scene next, LoadSceneMode mode)
  {
    // シーン切り替え後のスクリプトを取得
    var gameManager = GameObject.FindWithTag("GameManager").GetComponent<GameManagerScript>();

    // データを渡す処理
    gameManager.score = score;

    // イベントから削除
    SceneManager.sceneLoaded -= GameSceneLoaded;
  }

  private void SetTakeOverScore()
  {
    if (GameObject.FindGameObjectWithTag("GameManager") != null)
    {
      //スコアマネージャーを取得
      var manager = GameObject.FindGameObjectWithTag("GameManager");

      var scoreManager = manager.GetComponent<ScoreManager>();
      //引き継ぎ用にscoreを入れる
      score = scoreManager.GetScore();
    }
  }
}

としてスコアを引き継ぐことにしました.
これで完成!

とはなりませんでした.
引き継ぎ後のscoreが0になってしいました.

原因

原因は単純でScoreManager内のStart()で

ScoreManager.cs

void Start()
{
  score = 0;
}

としていることでした.
また属性をstaticにしていると思わぬところで
値が入って何処からきたんだこの値となっているところもありました.

UnityではSerializeFieldで初期化してしまうのが安全なのかなぁ.
あと,staticは基本使わなくていいなら使わないほうが良いのかもと思いました.

0
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?