OK, after looking at your code, you were referencing Bullet as something you were instantiating. What you need to do is differentiate Bullet the object you are copying, and Bullet the object you are using in the code. (not to mention, you can’t name them the same.)
Do yourself a favor, create a bullet at the end of the gun, Make sure to give it a rigidbody ONLY, no collider, then besides its name at the top uncheck the box for it. (disable it)
What follows are pieces for the components you need to fire at something.
First, lets assume that you have a gun, and you have to tell the gun that it is active. This is done when you pick up the gun, you reference the script and you set the activeUnit to true. Quite simple. Now, you instantiate the bullet that you had placed at the barrel of the gun and enable it, then add force to it to get it to move. You almost had this, but here is the updated code that should fix your problem.
var Bullet : GameObject;
var activeUnit=false;
function Update (){
if (activeUnit==true){
if(Input.GetButtonDown("Fire2")){
var bullet = Instantiate(Bullet, GameObject.Find("SpawnPoint").transform.position, Quaternion.identity);
bullet.enabled=true;
bullet.rigidbody.AddForce(transform.forward * 5000);
}
}
}
Next, as the bullet travels through the air it may or may not hit something. What we do is to check the last position against the current position and see if we hit anything in between. (remember I said the bullet should NOT have a collider so it wont hit its self.)
When it finally hits something, the bullet should 1) destroy it’s self, 2) send a message to the other object saying it should take some damage. So here is the code for the bullet. (very simple, more could be added to make it do things when it is destroyed)
var damage : float=5.0;
private var lastPosition : Vector3;
function OnEnable () {
lastPosition=transform.position;
}
function LateUpdate(){
var hit : RaycastHit;
var ray : Ray=Ray(lastPosition, transform.position - lastPosition);
var dist = Vector3.Distance(transform.position, lastPosition);
if(Physics.Raycast(ray, hit, dist)){
hit.collider.gameObject.SendMessage("TakeDamage", damage, SendMessageOptions.DontRequireReceiver);
Destroy(gameObject);
}
lastPosition=transform.position;
}
The last thing is the part where something takes damage. This is a basic health script that could be integrated into anything, or just stand alone. It has the receiving function “TakeDamage” which is required by the bullet, and once it takes some damage, it asks if it is dead yet. If so, it destroys the object. (again, this could be far more complex depending how over dramatic your people want to die in.) So here’s the code:
var hitPoints=100.0;
function TakeDamage(amount : float){
hitPoints-=amount;
if(hitPoints <= 0.0){
Destroy(gameObject);
}
}