- Home /
cannot cast from source type to destination type while instantiating?
hello everyone i am having an issue with my code below ,i am getting the invalid cast exception: cannot cast from source type to destination type and i am getting it twice when i hit "return" with pistol being a prefab
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class weaponicon : MonoBehaviour {
// Use this for initialization
public Transform pos;
public GameObject pistol;
void Start () {
}
// Update is called once per frame
void Update () {
}
void OnTriggerStay(Collider other)
{
if ((Input.GetKeyDown (KeyCode.Return)) && (other.gameObject.name == "pistol_icon")) {
Destroy (other.gameObject);
GameObject gun = Instantiate(pistol, pos.position, Quaternion.identity) as GameObject;
gun.transform.parent = pos;
}
}
}
I don't think the error is co$$anonymous$$g from this code.
But everything was working fine until i added this script : \ any idea what could be causing the error?
of you try finding the passage where the error is caused, either by debugging or breakpoints, we might be able to help.
you don't need to cast the gun to a gameobject… it already is of type GameObject. that wouldn't cause the error though, look at the error in the console and it will tell you from what line of what script the error happens at.
Answer by yade_123 · Jul 19, 2018 at 12:33 PM
I found a solution! by using resources.load the script worked fine i replaced line 25 and onwards with these lines and it works fine although i guess i never found the issue but thanks for the response guys the code:
GameObject gun = Instantiate(Resources.Load("pistol",typeof(GameObject))) as GameObject; gun.transform.position = pos.position; gun.transform.parent = pos;
Your answer
