- Home /
Help with getting a bullet to move.
I have a short script that is meant to spawn a bullet at the position of an empty object at the end of a gun and shoot it forward. However, while the bullet does spawn, it just sits there, and gives me this error:
InvalidCastException: Cannot cast from source type to destination type. Gun.Fire ()(at Assets/Scripts/Gun.js:12)
Here's my code:
var Bullet : Rigidbody;
var Spawn : Transform;
var BulletSpeed : float = 1000;
function Update () {
if(Input.GetButtonDown("Fire1")){
Fire();
}
}
function Fire(){
var bullet1 : Rigidbody = Instantiate(Bullet,Spawn.position,Spawn.rotation);
bullet1.AddForce(bullet1.transform.forward*BulletSpeed);
}
I just tested your code, and it worked fine. I could not reproduce the error.
Well, I'm following a tutorial on YouTube, and some people have been reporting the same problem, so it hasn't been just me. Could this possibly be due to the version of Unity I'm using (4.0)?
Did you attach this code to something like the camera or a FPS perfab or something. Just off the top of my head I have done that many many times before
This code is attached to the object serving as a gun, in this case a cube, which is attached to the a weapon camera. Here's what the Inspector of it looks like:
Here's where it is in the hierarchy:
I don't doubt you are having an error, and it is unlikely but possible to be the version of Unity. But if I cannot reproduce it using your script, it indicates a more subtle problem than the typical errors of this type. I'm running Unity version 4.01f2.
What happens if you use a different prefab for the bullet? Any chance the bullet script (if any) is deleting the rigidbody? What happens if you change your code to do this:
var bullet1 : GameObject = Instantiate(Bullet,Spawn.position,Spawn.rotation);
bullet1.rigidbody.AddForce(bullet1.transform.forward*BulletSpeed)
;
Answer by tklarenbeek · Mar 16, 2013 at 10:08 PM
I figured it out based off of KingKongFu's comment. Simply moving the code to be on the First Person Controller instead of the gun fixed it.
Answer by tklarenbeek · Mar 16, 2013 at 10:14 PM
I managed to figure it out. Turned out all I had to do was take the script off the gun and then just put it back on again.
Your answer
Follow this Question
Related Questions
Shooting & Animation Problem 1 Answer
Control amount of bullets 2 Answers
Shooting multiple bullets 2 Answers
Bullet Collision Issues 1 Answer
I Want To Shoot Bullets Correctly. 2 Answers