[英]Unity 2D Change sprite from a list of sprites
我在2D游戲中有一個gameObject作為精靈,然后在另一個腳本中,我在Sprite數組中有一個2D紋理數組。 我簡單地想更改sprite的sprite屬性,但得到錯誤“對象引用未設置為對象的實例”。 這是在一個腳本中拋出錯誤的行:
this.gameObject.GetComponent<SpriteRenderer> ().sprite = GameObject.Find ("UIM").GetComponent<Manager> ().spriteImages [1];
當數組位於不同的腳本中時,在與我嘗試從其訪問的場景不同的場景中附加到對象“ UIM”的對象(不確定是否會引起問題)的定義如下:
public Sprite[] spriteImages = new Sprite[5];
為什么會出現此錯誤? 我已經用紋理填充了數組,所以看不到問題。
您正在嘗試從另一個場景訪問腳本和變量。 每次加載新場景時,統一時,舊場景值將被破壞,並導致“對象引用未設置為對象實例”錯誤。 您可以通過調用DontDestroyOnLoad來使告知對象不要破壞將來場景中所需的對象。 這將允許游戲對象在整個場景中持續存在。 您還需要記住的另一件事是,如果您要返回舊場景,在該場景中將對象UIManager標記為dontdestroyonload,請確保從場景中刪除並管理下一個實例,然后重新加載場景,否則無論何時繼續加載該場景,使用UImanager的舊場景,它將繼續在整個場景中堆積其實例。 與dontdestroyonload結合使用的示例應該足以解決您的問題。 這是Unity API中顯示的片段,您可以參考:
void Awake()
{
GameObject[] objs = GameObject.FindGameObjectsWithTag("music");
if (objs.Length > 1)
{
Destroy(this.gameObject);
}
DontDestroyOnLoad(this.gameObject);
}
你可以試試:
public GameObject[] objs =
SceneManager.GetSceneByName(sceneToLoad).GetRootGameObjects();
foreach(GameObject go in objs)
{
if(go.name == "UIM")
{
this.gameObject.GetComponent<SpriteRenderer> ().sprite =
go.GetComponent<Manager> ().spriteImages [1];
break;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.