我有一个名为
GamePiece
的脚本,它附在预制件上。现在我想从包含所有预制件的GamePiece[] gamePieces
中生成随机游戏片段。
private IEnumerator SpawningRandomObjects()
{
Debug.Log("in SpawningRandomObjects");
yield return new WaitForSeconds(Random.Range(2f, waitSpawnTime));
Vector3 randomPosition = RandomPosition();
GamePiece spawned = Instantiate<GamePiece>(RandomGamePiece(gamePieces), randomPosition, Quaternion.identity);
Debug.Log("second to last line in SpawningRandomObjects"); //never comes to this line
//yield return new WaitUntil(() => drinkRef.FreezeSpawn());
}
private GamePiece RandomGamePiece(GamePiece[] gamePieces)
{
return gamePieces[Random.Range(0, gamePieces.Length)];
}
我不太明白如何在游戏中实例化它们,因为
Instantiate()
抛出以下错误:
InvalidCastException: Unable to cast object of type 'GameObject' to type 'GamePiece'.
at UnityEngine.Object.Instantiate[T] (T original, UnityEngine.Vector3 position, UnityEngine.Quaternion rotation) [0x00000] in <00000000000000000000000000000000>:0
at SpawnObjects+<SpawningRandomObjects>d__16.MoveNext () [0x00000] in <00000000000000000000000000000000>:0
at UnityEngine.SetupCoroutine.InvokeMoveNext (System.Collections.IEnumerator enumerator, System.IntPtr returnValueAddress) [0x00000] in <00000000000000000000000000000000>:0
错误是因为当您调用
Instantiate
而不是对象时,您传递的是附加到预制件的脚本组件。请从 Unity 的官方文档中阅读有关Instatiate的更多信息。
现在要修复您的错误,您需要引用您的 Prefab 并将其传递给
Instatiate
方法。要做到这一点,而不是拥有一个数组GamePiece[] gamePieces
,您必须将其更改为这个GameObject[] gamePieces
并添加所有预制件。如果您只有 1 个预制件,则不需要任何数组或列表,您可以直接使用单个引用。
应该是这样的:
GameObject spawned = Instantiate<GameObject>("ReplaceWithPrefabReference", randomPosition, Quaternion.identity);
Instantiate()
返回一个 gameobject
,而不是你的组件。它将复制您的组件所附加的游戏对象(这是您想要的),因为如果不附加到组件就无法存在gameobjects
如果你只想要组件,那么只需在新的
GetComponent
上调用
gameobject
GamePiece spawned = Instantiate<GamePiece>(RandomGamePiece(gamePieces), randomPosition, Quaternion.identity).GetComponent<GamePeice>();