❤❤Fungus新課程即將發布,快寫問卷拿優惠❤❤

2017年2月22日 星期三

Unity 場景切換 DontDestroyOnLoad + SceneManager 教學


==PlayerController==

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerController : MonoBehaviour {
    Rigidbody2D playerRigidbody2D;
    public float speed;

    void Start () {
        playerRigidbody2D = GetComponent<Rigidbody2D>();  
 }
 
 void Update () {
        if (Input.GetKey(KeyCode.RightArrow))
        {
            playerRigidbody2D.AddForce(Vector2.right * speed);
        }

        if (Input.GetKey(KeyCode.LeftArrow))
        {
            playerRigidbody2D.AddForce(Vector2.left * speed);
        }
 }
}



==GameManager==

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

public class GameManager : MonoBehaviour {
    //singleton
    //單例模式
    static GameManager instance;
    public int money;
    void Awake () {
        if (instance==null)
        {
            instance = this;
            DontDestroyOnLoad(this);
            name = "最初的遊戲管理物件";
            money = 0;
        }
        else if (this!=instance)
        {
            string sceneName = SceneManager.GetActiveScene().name;
            Debug.Log("刪除場景"+sceneName+"的"+name);
            Destroy(gameObject);
        }       
 }
 
 void Update () {
  
 }
}



==Door==

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

public class Door : MonoBehaviour {

    [Header("連接到某場景")]
    public string goToTheScene;
    void OnTriggerEnter2D(Collider2D other)
    {
        if (other.CompareTag("玩家"))
        {
            SceneManager.LoadScene(goToTheScene);
        }
    }

}



==Gold==

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Gold : MonoBehaviour {

    GameManager gameManager;
    void Awake()
    {
        gameManager = FindObjectOfType<GameManager>();
    }
    void OnTriggerEnter2D(Collider2D other)
    {
        if (other.CompareTag("玩家"))
        {
            gameManager.money += 10;
            Debug.Log("金錢="+gameManager.money);
        }
    }

}

2 則留言:

  1. 如果我只想在2個場景DontDestroyOnLoad() 進入第3個場景便刪除 那該怎麼做呢?

    回覆刪除
  2. 不想動到原本的GameManager程式碼的話
    可以新開一個腳本 取名DestroyGameManager

    using UnityEngine;

    public class DestroyGameManager : MonoBehaviour {

    void Start () {
    //尋找所有的GameManager組件(以防萬一,數量可能會有兩個以上)
    GameManager[] gameManager = FindObjectsOfType();

    if (gameManager.Length > 0)//如果找到的GameManager組件數量大於0的話
    {
    //一個個刪除該組件所屬的遊戲物件
    foreach (var g in gameManager)
    {
    Destroy(g.gameObject);
    Debug.Log("強制刪除 "+g);
    }
    }
    else
    {
    Debug.Log("找不到任何GameManager可刪除");
    }
    }
    }


    ========================

    然後在第3場景裡可開一個遊戲物件 取名為"強制刪除GameManager"
    然後把這個腳本附掛上去就可以了

    喜歡我教學的話請多多幫我推廣Youtube頻道喔~

    回覆刪除

留言給作者加油打氣