![](/img/trans.png)
[英]gameObject.GetComponent<T> != null is always true. How?
[英]gameObject.GetComponent returning null
我有一個問題。
在我的一個腳本中,當我嘗試獲取組件時,它在控制台中返回此錯誤,並返回null:“ NullReferenceException:在需要對象實例的位置找到了null值。”
我不知道為什么,因為在其他文件中,我使用的過程效果很好。
這是我的代碼流:第一個-GameController.cs
public class GameController : MonoBehaviour {
private SpawningPositions spawningPositions; //IT WORKS
private void Awake()
{
spawningPositions = GetComponent<SpawningPositions>(); //IT WORKS
}
void Start()
{
if (enemyWaveTypes.Length != 0 && wavesNumberEnemy.Length != 0)
{
StartCoroutine(SpawnShips());
}
}
IEnumerator SpawnShips()
{
while (true)
{
for (int i = 0; i < wavesNumberEnemy[waveCounter]; i++)
{
spawningPositions.SpawnRandom(enemyShip); //IT WORKS // NEXT SCRIPT
}
waveCounter++;
yield return new WaitForSeconds(waveTimingRatio);
}
}
}
第二個-SpawningPositions.cs
public class SpawningPositions : MonoBehaviour {
GeoData geoData; //IT WORKS
private void Awake()
{
geoData = GetComponent<GeoData>(); //IT WORKS
}
public void SpawnRandom(Transform enemyShip)
{
Vector3 spawnPosition;
Tuple<int, float> tuple = geoData.GetRandomOuterBoundary(); //IT WORKS (i've got a custom class for Tuples)
int randomSpawn = tuple.Item1;
float randomPosition = tuple.Item2;
spawnPosition = geoData.GetRandomPointIn(tuple);
Quaternion spawnRotation = Quaternion.identity;
var myEnemy = Instantiate(enemyShip, spawnPosition, spawnRotation);
myEnemy.gameObject.AddComponent<FixedPointAndGo>(); // NEXT SCRIPT
}
}
最后一個是我遇到問題的地方-FixedPointAndGo.cs
public class FixedPointAndGo : MonoBehaviour {
GeoData geoData; // DOESN'T WORK!!!
private void Awake()
{
geoData = gameObject.GetComponent<GeoData>(); // DOESN'T WORK!!! return NULL
}
private void Start()
{
endPos = new Vector3(
Random.Range(
(geoData.horizontalInLimits.x - 2), // DOESN'T WORK!!!
(geoData.horizontalInLimits.y - 2) // DOESN'T WORK!!!
),
0,
Random.Range(geoData.verticalInLimits.x, geoData.verticalInLimits.y) // DOESN'T WORK!!!
);
}
}
為什么當我嘗試在第二個腳本而不是第三個腳本中添加組件GeoData
時起作用? 我不明白。
我試圖在此論壇和文檔中搜索解決方案,但尚未找到任何東西。
提前致謝
geoData = gameObject.GetComponent<GeoData>(); // DOESN'T WORK!!! return NULL
注意變量“ gameObject
”。 這是指此腳本( FixedPointAndGo
)附加到的FixedPointAndGo
。
這意味着僅當GeoData
腳本未附加到您的FixedPointAndGo
腳本附加到的FixedPointAndGo
, gameObject.GetComponent<GeoData>()
才返回null
。
將GeoData
附加到您的FixedPointAndGo
腳本附加到的相同FixedPointAndGo
。
如果將GeoData
附加到另一個GeoData
,並且您想訪問它,則在訪問附加到它的GeoData
組件之前,先找到該GeoData
。
GameObject obj = GameObject.Find("NameOfGameObjectGeoDataIsAttachedTo");
geoData = obj.GetComponent<GeoData>();
最后,如果GeoData
腳本附加到相同的FixedPointAndGo
腳本上,但是您仍為null
則錯誤地將另一個FixedPointAndGo
腳本附加到一個空的FixedPointAndGo
或另一個未附加GeoData
腳本的GeoData
。
找到該FixedPointAndGo
並FixedPointAndGo
刪除FixedPointAndGo
腳本。 您可以選擇“ FixedPointAndGo
腳本,然后轉到“ 資產 ---> 在場景中查找引用”並刪除腳本來完成此操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.