- Home /
How to detect which player shot the bullet?
A player shoots a bullet:
if (Input.GetButtonDown("Fire1"))
{
Rigidbody bulletInstance;
bulletInstance = Instantiate(Bullet, barrelEnd.position, barrelEnd.rotation) as Rigidbody;
bulletInstance.AddForce(barrelEnd.forward * Velocity);
}
And then when my bullet hits the enemy I want to know which players bullet it was that shot the bullet. This is in my Bullet class:
void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.tag == "Enemy")
{
collision.gameObject.SendMessage("Hit");
Destroy(gameObject);
}
}
Basically what I want to do is to be able add to the score of the player who shot the bullet. Any ideas?
Answer by aldonaletto · Sep 28, 2013 at 07:40 PM
You should place a reference to the shooter in the Bullet script when shooting - like this (supposing that the bullet script is called Bullet.cs):
if (Input.GetButtonDown("Fire1"))
{
Rigidbody bulletInstance;
bulletInstance = Instantiate(Bullet, barrelEnd.position, barrelEnd.rotation) as Rigidbody;
bulletInstance.AddForce(barrelEnd.forward * Velocity);
// set the shooter variable in the bullet script:
bulletInstance.GetComponent<Bullet>().shooter = transform;
}
Obviously, you should declare a public Transform variable shooter in the bullet script
public Transform shooter;
void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.tag == "Enemy")
{
collision.gameObject.SendMessage("Hit");
Destroy(gameObject);
shooter.SendMessage("AddToScore", 5); // add 5 points to the shooter's score
}
}
And some script attached to the player should have the function AddToScore that would effectively increment the score:
void AddToScore(int points){
score += points;
}
hello, i would like to know whether this is possible in the case where we instantiate bullet in a [command](Cmdshoot())??
But you never set your shooter equal to anything? You just say there is a public transform shooter. Since the bullet is spawned, you cannot assign it in the inspector. So how do you assign it during runtime?
You will find the answer in the provided code....
bulletInstance.GetComponent<Bullet>().shooter = transform;
Your answer
Follow this Question
Related Questions
Why will the bullets sometimes not show up in the game view when the player shoots? 0 Answers
How can I match the score script to my fire script, on a per click basis 1 Answer
How can I make bullets shoot out of a plane? 1 Answer
Survival Shooter Tutorial: Why Isn't the Score Increasing When I Shoot an Enemy Down? 0 Answers
RayCast Shooting And Errors 1 Answer