- Home /
Firing different bullets
I'm working on some small project here. What I basically want to do is when a key is pressed the player changes the bullets he fires. Now I know how to fire bullets. But the changing of the bullets when key is pressed is something I cant figure out. I would love to get some guidance or be pushed into the right direction so I can make this.
Did you tried "switch" statement and then "case 1","case 2"? Here is good link for "switch" statement. Link
how are you firing these bullets, could we see your code?
Answer by nightowl79a · Jan 20, 2015 at 02:16 PM
What I would do is make a array or list of prefabs for the bullets. Then I would make an int variable(curBullet for exsample) to store the current bullet. When the player presses the change weapon button he would change the curBullet variable, and I would instatiate the bullet matching the position in the array. Here is what the code would look like if that was a bit confusing:
public class FireBullets : MonoBehaviour {
public GameObject[] bullets;
int curBullet = 0;
void Update ()
{
if (Input.GetKey(KeyCode.Tab))
{
// Add one to the curBullet variable when the player presses tab.
//This will allow you to fire the next bullet in the bullets Array
curBullet++;
// If the curBullet is higher than the bullet array length set it back to 0
if (curBullet > bullets.Length)
{
curBullet = 0;
}
}
if (Input.GetButton("Fire1"))
{
// Fire the bullet matching is position in the array of bullets
Instantiate(bullets[curBullet], transform.position, transform.rotation);
}
}
}
Answer by sniper43 · Jan 20, 2015 at 02:29 PM
Are you using a line renderer? In which case you should change the material/texture/hue.
If you are generating new objects for eact bullet, just change the type of bullet being instantiated by having a GameObject that gets spawned and using your listener to adjust what that object is.
Example: using UnityEngine; using System.Collections;
class asd
{
public GameObject bullet;
void Update()
{
if( Input.getButton( "valueForFiring" ) )
Instantiate(bullet);
}
public void changeBullet( GameObject newBullet)
{
bullet = newBullet;
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613180943im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Shooting with Limited Ammo 2 Answers
Need hep with pooling(call Cs in Js) 0 Answers
Getting Bullets to fire in Direction of Gun Barrel 1 Answer