- Home /
Why do I get: "Cannot cast from source type to destination type"?
I'm working on a project where a cannon shoots a cannonball. I've manage to create a simple code for shooting the cannonball. It worked just fine. Then I fumbled on the code and as it didn't work I changed back to the original. And now I always get the message 'Cannot cast from source type to destination type'. Here is the script that handles the shooting:
using UnityEngine;
using System.Collections;
public class shootCanonnball : MonoBehaviour {
public Rigidbody cannonball;
public Transform shotSpawn;
public float shootForce;
void Update () {
if (Input.GetMouseButtonDown (0)) {
GameObject cannonB = (GameObject)Instantiate(cannonball, shotSpawn.position, shotSpawn.rotation);
cannonB.GetComponent<Rigidbody>().AddForce(transform.up * shootForce, ForceMode.Impulse);
}
}
}
I've looked up the other answers about this problem, but none of them work for me. It just seems like Unity made up an error and I don't know from where. I even created a new project with new objects in it and wrote the code again. Again, Same error on a different project.
Answer by YoungDeveloper · Aug 13, 2015 at 01:41 PM
public Rigidbody cannonball;
should be a gameobject prefab
public GameObject cannonball;
Actually it would make more sense to change the cast since he actually needs the rigidbody reference:
Rigidbody cannonB = (Rigidbody)Instantiate(cannonball, shotSpawn.position, shotSpawn.rotation);
cannonB.AddForce(transform.up * shootForce, Force$$anonymous$$ode.Impulse);
You almost never want to use the type "GameObject" since in most cases you need to access one of the components. For a generic "object" i always use "Transform". "GameObject" is the most useless type (from a scripting point of view).
Thank you very much for the help and for the tip about GameObject.
Your answer
Follow this Question
Related Questions
Recoil on self-object 1 Answer
How to delay time reset on collision? 2 Answers
Unity3D Pressure Plate request. 3 Answers
What is wrong with this shooting script? 2 Answers
Fast object on collider not working 1 Answer