• Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
1
Question by MajorParts · Sep 30, 2014 at 12:02 AM · c#laserfiring

Switching Firing Modes

I've searched all over to find a way to do this and spent 2 days doing so with no luck.

So far, I have an x-wing style ship with 4 laser turrets. I have a script to fire all 4 at once, but I need to find a way, to switch between 3 firing modes...all 4, 2 turrets alternating with the other 2 and one after the other in order.

This is the script for all 4 (could this be done any tidier also?)....

using UnityEngine; using System.Collections;

public class XW_Shooting : MonoBehaviour {

 public GameObject bullet_prefab;
 public float bulletImpulse = 20f;
 public float xwFireRate = 1f;
 private float xwFire = 0.0f;
 Transform gunTip1;
 Transform gunTip2;
 Transform gunTip3;
 Transform gunTip4;
 public AudioClip shoot;

 void Start () 
 {
     gunTip1 = GameObject.Find ("GuntipLT").transform;
     gunTip2 = GameObject.Find ("GuntipRT").transform;
     gunTip3 = GameObject.Find ("GuntipLB").transform;
     gunTip4 = GameObject.Find ("GuntipRB").transform;


 }


             
 // Update is called once per frame

 void Update (){
     if (Input.GetButton ("Fire1") && Time.time > xwFire) {
         xwFire = Time.time + xwFireRate;

         GameObject thebullet = (GameObject)Instantiate (bullet_prefab, gunTip1.transform.position + transform.forward, transform.rotation);
         thebullet.rigidbody.AddForce (transform.forward * bulletImpulse, ForceMode.Impulse);
         audio.PlayOneShot(shoot);

         gunTip2 = GameObject.Find ("GuntipRT").transform;

         GameObject thebullet2 = (GameObject)Instantiate (bullet_prefab, gunTip2.transform.position + transform.forward, transform.rotation);
         thebullet2.rigidbody.AddForce (transform.forward * bulletImpulse, ForceMode.Impulse);
         audio.PlayOneShot(shoot);
         
         gunTip3 = GameObject.Find ("GuntipLB").transform;
         
         GameObject thebullet3 = (GameObject)Instantiate (bullet_prefab, gunTip3.transform.position + transform.forward, transform.rotation);
         thebullet3.rigidbody.AddForce (transform.forward * bulletImpulse, ForceMode.Impulse);
         audio.PlayOneShot(shoot);
         
         gunTip4 = GameObject.Find ("GuntipRB").transform;
         
         GameObject thebullet4 = (GameObject)Instantiate (bullet_prefab, gunTip4.transform.position + transform.forward, transform.rotation);
         thebullet4.rigidbody.AddForce (transform.forward * bulletImpulse, ForceMode.Impulse);
         audio.PlayOneShot(shoot);


     }
 }

}

Thanks for looking!

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

2 Replies

· Add your reply
  • Sort: 
avatar image
2

Answer by robertbu · Sep 30, 2014 at 12:03 AM

Sometimes in solving a problem like this one, all the current code gets in the way, and it can be helpful to backup and solve the specific problem in simpler code.

 using UnityEngine;
 using System.Collections;
 
 public class Example : MonoBehaviour {
 
     public enum Sequence { ALLFOUR, TWOBYTWO, INORDER };
 
     public Sequence seq = Sequence.INORDER;
 
     void Update() {
         if (Input.GetKeyDown(KeyCode.Space)) {
             StartCoroutine(Fire(seq));
         }
     }
 
     IEnumerator Fire(Sequence seq) {
         switch(seq) {
         case Sequence.ALLFOUR:
             Fire(1);
             Fire(2);
             Fire(3);
             Fire(4);
             break;
         case Sequence.TWOBYTWO:
             Fire(1);
             Fire(2);
             yield return new WaitForSeconds(0.3f);
             Fire(3);
             Fire(4);
             break;
         case Sequence.INORDER:
             Fire(1);
             yield return new WaitForSeconds(0.3f);
             Fire(2);
             yield return new WaitForSeconds(0.3f);
             Fire(3);
             yield return new WaitForSeconds(0.3f);
             Fire(4);
             break;
         }
     }
 
     void Fire(int which) {
         Debug.Log ("Firing " + which);
     }
 }
Comment
Add comment · Show 4 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Kiwasi · Sep 30, 2014 at 12:09 AM 0
Share

This might break with "Not all code paths return a value". Put a yield return null in at the end of the coroutine to fix.

avatar image MajorParts · Sep 30, 2014 at 01:19 AM 0
Share

ok, great, thanks. I can see how that works...although I didn't make myself clear...your answer switches to the various fire modes ok, but the 2by2 and inorder sequences carry on through the cycle (which is ok if the button is held). I was looking for a way to step through each time the fire button is pressed, so inorder would fire LT the 1st time it is pressed, RT the 2nd time etc. I'm also having to define "thebullet" with a new number for each set or i get errors. I now have thebullet1 through to thebullet12....is this to be expected, or is this what boredmormom is refering to about the null statement?

avatar image robertbu · Sep 30, 2014 at 02:27 AM 0
Share

Given you new description, here is a bit of code. Whatever code changes the Sequence needs to set cycle to 0.

 using UnityEngine;
 using System.Collections;
 
 public class Bug25a : $$anonymous$$onoBehaviour {
 
     public enum Sequence { ALLFOUR, TWOBYTWO, INORDER };
     public Sequence seq = Sequence.INORDER;
 
     private int cycle = 0;
 
     void Update() {
         if (Input.Get$$anonymous$$eyDown($$anonymous$$eyCode.Space)) {
             Fire();
         }
     }
 
     void Fire() {
         switch(seq) {
         case Sequence.ALLFOUR:
             Launch(1);
             Launch(2);
             Launch(3);
             Launch(4);
             cycle = 0;
             break;
         case Sequence.TWOBYTWO:
             if (cycle == 0 || cycle == 1) {
                 Launch(1);
                 Launch(2);
                 cycle = 2;
             }
             else {
                 Launch(3);
                 Launch(4);
                 cycle = 0;
             }
             break;
         case Sequence.INORDER:
             Launch(cycle);
             cycle = (cycle + 1) % 4;
             break;
         }
     }
 
     void Launch(int which) {
         Debug.Log ("Firing " + which);
     }
 }



Note: I highly recommend putting guntips in an array. It would greatly simplify your code.

avatar image MajorParts · Sep 30, 2014 at 11:40 AM 0
Share

I'm sorry I didn't mention the key press thing beforehand. Very kind of you to continue to help me :) I shall try and incorporate these ideas into the script. I will look into arrays though, as I'm sure it could be less cluttered. It may even help with the audio being played in the correct 3d space...that's another thread though. Cheers

avatar image
0

Answer by Kiwasi · Sep 30, 2014 at 02:50 AM

You really need to sort our your plain English descriptions first. Code and structure will flow naturally from a decent functional description.

To answer based on your comments you could put a loop in that waits for input before firing the next bullet in @robertbu's solution.

 while (!Input.GetKeyDown(KeyCode.Space)) {
     yield return null;
 }

Pseudo code could look something like this

 var fireMode;

 void Start (){
     StartCoroutine("Fire")
 }

 IEnumerator Fire (){
     switch (fireMode){
     case 1:
         while (true){
             for (int i = 0; i<noOfGuns; i++){
                 yield return new WaitForSeconds(firingDelay);
                 while (!Input.GetKeyDown(KeyCode.Space)) yield return null;
                 FireGun(i);
             }
         }
     .. Other cases
     } 
 }
 
 public void ChangeFireMode (newFireMode){
     // Change fire mode
     StoptCoroutine("Fire")
     StartCoroutine("Fire")
 }

Alternatively you could use a collection to determine which gun to fire next and iterate through that. You could build a custom collection that automatically cycles through the guns infinitely.

Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image MajorParts · Sep 30, 2014 at 11:36 AM 0
Share

Yes, I apologize for not stating things. Sometimes these things are in my head for so long that I think I've mentioned them :) Thanks for the example, I shall get stuck into it again soon.

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Follow this Question

Answers Answers and Comments

3 People are following this question.

avatar image avatar image avatar image

Related Questions

Multiple Cars not working 1 Answer

Distribute terrain in zones 3 Answers

Making a bubble level (not a game but work tool) 1 Answer

transform.forward makes my GameObject Disappear 0 Answers

Shoot Laser 0 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges