bob smith
bob smith

Reputation: 29

Cannot convert type to type c#

So I am working on a game with unity using C# and I'm trying to make a clone then delete it. So the code I posted respawns the player and has sparks fly out when he respawns. This makes a clone of the sparks. I am having trouble deleting the sparks. I get the error message:

cannot convert type unityengine.transform to unityengine.gameobject via.....

so I need to know what is wrong with my code and why it is doing this.

so here is the whole 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 Transform spawnPrefab;

public IEnumerator RespawnPlayer () {
    //audio.Play ();
    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 here is the line it is messing up on

 GameObject clone = Instantiate (spawnPrefab, spawnPoint.position, spawnPoint.rotation) as GameObject;

Upvotes: 0

Views: 229

Answers (2)

Lincoln Cheng
Lincoln Cheng

Reputation: 2303

It is ok to instantiate as a transform, just destroy it's gameObject in your destroy line:

Transform clone = Instantiate(spawnPrefab, spawnPoint.position, spawnPoint.rotation) as Transform;
Destroy(clone.gameObject, 3f);

Upvotes: 1

Programmer
Programmer

Reputation: 125445

You get the error because your prefab is declared as a Transform when you did public Transform spawnPrefab;. So, you are Instantiating it as a Transform instead of GameObject.

To fix it, simply change

public Transform spawnPrefab;

to

public GameObject spawnPrefab;

Upvotes: 3

Related Questions