簡體   English   中英

在新場景中加載后,畫布不會啟用它

[英]Canvas wont enable it after got loaded in new scene

所以我有一個游戲對象,它在必要時加載新場景。 附加到游戲對象的腳本有一個變量,它保存對畫布元素的引用(畫布元素有一個進度條)。 問題是,在我加載一個新場景后,我想在該加載的場景中加載一個新場景,我失去了對畫布對象的引用,因為我無法將他設置為 DontDestroyOnLoad。

我所做的是將畫布元素(請參閱 start function() 中的注釋行)作為不會被破壞的游戲對象的子元素。完成后,我沒有收到我丟失的警告對象引用但它不會在 setNewNameAndLoadScene() 函數中啟用畫布。

我的意思是啟用 gui 不會出現在屏幕上,但它在層次結構中。 我檢查了它是否為空,而事實並非如此。 該程序通過代碼行運行沒有問題,但畫布沒有出現在游戲屏幕上。

第二次編輯:我剛剛檢查了(在運行時)如果我將我的畫布(它是我的游戲對象的子項)放在新加載場景的畫布中會怎樣。 發生的事情是它顯示了我的畫布。 但是我問我為什么將它放入場景畫布時會顯示它。 在我加載我的第一個場景之前,我的畫布不在場景畫布中,但仍然在游戲屏幕中顯示了進度條

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

public class SceneLoaderGameObject : MonoBehaviour {


private SceneLoader sl;
public Canvas cav; //loses reference when loading new scene

void Start () {
    sl = new SceneLoader ();
    cav.GetComponent<Canvas> ().enabled = false;
    DontDestroyOnLoad (this.gameObject);
    DontDestroyOnLoad (this);
    DontDestroyOnLoad (this.gameObject.transform.GetChild(0).GetComponent<Canvas>()); 
}

public void setNewNameAndLoadScene(string name){

    if(name.Length ==0)
        throw new UnityException("length 0");

    if (cav != null) {
        Slider slid = cav.transform.GetChild (1).GetComponent<Slider> ();
        Text tx = cav.transform.GetChild (2).GetComponent<Text> ();
        Button bttn = cav.transform.GetChild (3).GetComponent<Button> ();

        sl.setNewScene (name);
        sl.setSliderAndTextToChange (slid, tx);
        bttn.onClick.AddListener (() => activateNewScene ());
        cav.GetComponent<Canvas> ().enabled = true;
        StartCoroutine (sl.LoadAsynchron (name, bttn));

    }

}

public void  activateNewScene(){
    sl.AsgetOP().allowSceneActivation=true;

 }
}

只需使用下面的代碼來制作單例並獲取滑塊的公共游戲對象引用或在場景加載時您想要激活-停用的任何內容。 例如,如果您有控制畫布組件的游戲管理器,則使單例對象和引用對象相互關聯。 代碼源在這里

public class SceneLoaderSingleton : MonoBehaviour
{

    //Static instance of SceneLoaderSingleton which allows it to be accessed by any other script.
    public static SceneLoaderGameObject instance = null;    

    //Awake is always called before any Start functions
    void Awake()
    {
        //Check if instance already exists
        if (instance == null)

            //if not, set instance to this
            instance = this;

        //If instance already exists and it's not this:
        else if (instance != this)

            //Then destroy this. This enforces singleton pattern, meaning there can only ever be one instance of a SceneLoaderSingleton.
            Destroy(gameObject);    

        //Sets this to not be destroyed when reloading scene
        DontDestroyOnLoad(gameObject);            
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM