Search Unity

InvalidCastException: Cannot cast from source type to destination type. ObjectSpawner.SpwanTarget ()

Discussion in 'Scripting' started by Niki.j, Sep 17, 2014.

  1. Niki.j

    Niki.j

    Joined:
    Oct 17, 2012
    Posts:
    157
    Hi,

    I am trying to spawn objects in my game and come with an issue "cannot cast from source type to destination type"……
    Cannot find my mistake…can anyone help me on this..

    using UnityEngine;
    using System.Collections;

    public class MovingObject
    {
    public DirectionEnum direction;
    public Transform transform;

    public MovingObject(DirectionEnum dir, Transform trans)
    {
    direction = dir;
    transform = trans;
    }
    }

    [System.Serializable]
    public enum DirectionEnum
    {
    down = 2
    }

    public class ObjectSpawner : MonoBehaviour
    {
    public Transform newObj;
    public Transform targetPrefeb;
    private int spwanPoint = 5;
    public DirectionEnum spawnDirection = DirectionEnum.down;
    public static ObjectSpawner SP;
    private float lastSpawnTime;
    public float spawnInterval;

    void Awake()
    {
    SP = this;
    spawnInterval = Random.Range(3.5f, 5.5f);
    lastSpawnTime = Time.time + Random.Range(0.0f, 1.5f);
    }

    void Start()
    {
    SpwanTarget();
    }

    void Update()
    {
    if ((lastSpawnTime + spawnInterval) < Time.time)
    {
    SpwanTarget();
    }
    }

    void SpwanTarget ()
    {
    lastSpawnTime = Time.time;

    newObj =(Transform)Instantiate(targetPrefeb,new Vector3(Random.Range(-spwanPoint,spwanPoint),7,0), Quaternion.identity);//I am getting the issue with this line of code……but it seems perfectly fine to me….

    MovingObject movObj = new MovingObject(spawnDirection, newObj);
    GameManager.SP.AddTarget(movObj);
    }
    }