[英]My GameObject always stays inactive, SetActive(true) doesn't work and the coroutine won't start
我將許多預制件存儲在一個數組中,並通過單擊一個按鈕一次實例化一個。 該對象出現,但始終處於非活動狀態。
我已經搜尋了幾個小時的答案,並嘗試了很多,但問題仍然存在。 我希望可以問問,即使有幾個類似的問題,但沒有一個答案可以解決我的問題。 就像我已經描述過的那樣,我想在每次單擊按鈕時從數組中實例化一個GameObject,並且確實出現了該對象,但是當我嘗試在其上啟動協程時(如果有幫助,它是一個IEnumerator,它將使Object淡出。處理它的顏色Alpha通道),我總是收到一條錯誤消息,說GameObject未激活。 我無法通過編寫myPrefab.gameObject.SetActive(true)將其設置為活動狀態,並且嘗試在代碼中的多個位置調用它。 它始終保持不活動狀態。 有誰知道可能是什么問題?
public class Class1 : MonoBehaviour
{
[SerializeField]
private MyClass[] myPrefabs;
private MyClass myCurrentPrefab;
private int myIndex;
public void ButtonEffect()
{
InstantiatePrefab();
myCurrentPrefab.OnButtonEffect();
}
private void InstantiatePrefab()
{
myIndex = Random.Range(0, myPrefabs.Length);
myCurrentPrefab = myPrefabs[myIndex];
Instantiate(myCurrentPrefab);
}
}
public class MyClass : MonoBehaviour
{
private SpriteRenderer mySprite;
private void Start()
{
mySprite = GetComponent<SpriteRenderer>();
}
private void Awake()
{
this.gameObject.SetActive(true)
}
private void OnButtonEffect()
{
StartCoroutine(FadeOut(mySprite, 3));
}
public IEnumerator FadeOut(SpriteRenderer spriteToFade, float duration)
{
//DoFadeOutStuff
}
}
在這里,我嘗試將對象在其自己的代碼的Awake函數中設置為活動狀態,但同時也在Class1函數和其Start函數中對其進行嘗試。 我也嘗試過在foreach循環中為整個數組處理它。 總是相同的結果。 我要做的就是將其設置為活動狀態,現在我什至不在乎淡出的東西是否正常工作。 首先,我認為這是因為我的實例化對象是一個克隆,但是我找不到任何有關它的信息,因此即使解決方案很明顯,也請幫忙!
問題是您要引用實際的預制件本身,而該預制件在場景中實際上並不活躍。 您需要創建一個游戲對象並將其值設置為實例化的預制件。 以下應該工作
using UnityEngine;
public class Class1 : MonoBehaviour
{
[SerializeField]
private GameObject[] myPrefabs;
public void ButtonEffect()
{
var go = InstantiatedPrefab();
go.GetComponent<MyClass>().OnButtonEffect();
}
private GameObject InstantiatedPrefab()
{
var index = Random.Range(0, myPrefabs.Length);
return Instantiate(myPrefabs[index]);
}
}
using System.Collections;
using UnityEngine;
public class MyClass : MonoBehaviour
{
private SpriteRenderer mySprite;
private void Start()
{
mySprite = GetComponent<SpriteRenderer>();
}
public void OnButtonEffect()
{
StartCoroutine(FadeOut(mySprite, 3));
}
private IEnumerator FadeOut(SpriteRenderer spriteToFade, float duration)
{
print("FadeOut");
yield return 0;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.