InvalidCastException: Cannot cast from source type to destination type.
I'm having a huge issue, as a unity noob i've looked over the already completed answers but I have no idea how to apply what fixes they've found to what I'm doing.
This is my code
using UnityEngine;
using System.Collections;
public class gameMaster : MonoBehaviour {
public static gameMaster gm;
void Start () {
if (gm == null) {
gm = GameObject.FindGameObjectWithTag ("GM").GetComponent<gameMaster>();
}
}
public Transform playerPrefab;
public Transform spawnPoint;
public float spawnDelay = 2;
public GameObject spawnPrefab;
public IEnumerator RespawnPlayer () {
yield return new WaitForSeconds (spawnDelay);
Instantiate (playerPrefab, spawnPoint.position, spawnPoint.rotation);
GameObject clone = Instantiate (spawnPrefab, spawnPoint.position, spawnPoint.rotation) as GameObject;
Destroy (clone, 3f);
}
public static void KillPlayer (Player player) {
Destroy (player.gameObject);
gm.StartCoroutine(gm.RespawnPlayer());
}
}
and this is the error
InvalidCastException: Cannot cast from source type to destination type.
UnityEngine.Object.Instantiate[GameObject] (UnityEngine.GameObject original, Vector3 position, Quaternion rotation) (at C:/buildslave/unity/build/Runtime/Export/UnityEngineObject.cs:207)
gameMaster+<RespawnPlayer>c__Iterator0.MoveNext () (at Assets/gameMaster.cs:21)
UnityEngine.SetupCoroutine.InvokeMoveNext (IEnumerator enumerator, IntPtr returnValueAddress) (at C:/buildslave/unity/build/Runtime/Export/Coroutines.cs:17)
Thank you for helping, i know this is probably a stupid noob mistake but, I have to learn somehow.
Answer by UnityCoach · Dec 06, 2016 at 10:25 PM
Try this instead :
GameObject clone = (GameObject) Instantiate (spawnPrefab, spawnPoint.position, spawnPoint.rotation);
Ah, you can't instantiate a transform component, well, you somehow can, but can't cast it to a GameObject
public Transform playerPrefab;
// change to:
public GameObject playerPrefab;
Your answer
Follow this Question
Related Questions
InvalidCastException: Cannot cast from source type to destination type. 1 Answer
InvalidCastException: Cannot cast from source type to destination type. 1 Answer
NullReferenceException on Invoke in another class 1 Answer
InvalidCastException: Cannot cast from source type to destination type. 2 Answers