• 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
0
Question by coldfire1500 · Dec 27, 2020 at 12:08 AM · unity 2dshootingbulletsidescrollerweapon system

Optimizing Code

HI, so I've been learning c# for the past weeks and it's been a nice journey. I have this Code that I've made using tutorials and myself and I'm pretty sure is not optimized at all. I've realized that following tutorials from A to D only makes me start copy pasting code as I reach point E so I decided to try to get as much as I could do myself searching on the internet and solving problems myself instead of follwing thos tutorials, however there is a limit on what I can do and I'm pretty sure I've made the code not optimized at all since my problem solving is not good, so I'd like to ask for help in how to optimize this.

public class Weapon : MonoBehaviour {

 [Header("ShotPoint")]
 public Transform horizontalShotPoint;
 public Transform VerticalShotPoint;
 
 [Header("CanShoot")]
 public bool xCanShoot = true;
 public bool yCanShoot = true;

 [Header("Recoil")]
 public float horizontalRecoil;
 public float verticalRecoil;

 [Header("Projectile")]
 public GameObject Projectile;
 public float xProjectileSpeed;
 public float yProjectileSpeed;

 [Header("Cooldown")]
 public float horizontalStartTimeBtwShots;
 public float VerticalStartTimeBtwShots;

 Rigidbody2D rb;
 Player player;
 private float timeBtwShots;

 void Start() {
     rb = GetComponent<Rigidbody2D>();
     player = GetComponent<Player>();
 }

 void Update() {
     if(timeBtwShots <= 0) {
         if(Input.GetKey(KeyCode.DownArrow)) {
             xCanShoot = false;
         } else {
             xCanShoot = true;
         }
         if(Input.GetButtonDown("Fire1") && xCanShoot) {
             horizontalShoot();
             timeBtwShots = horizontalStartTimeBtwShots;
         } else if (Input.GetKey(KeyCode.DownArrow) && Input.GetButtonDown("Fire1") && yCanShoot){
             CooldownBar.isntance.UseStamina(100);
             player.anim.SetBool("ShootDown", true);
             VerticalShoot();
             timeBtwShots = VerticalStartTimeBtwShots;
         }
     } else {
         timeBtwShots -= Time.deltaTime;
     }
 }
 
 void horizontalShoot() {
     if(player.facingRight == true) {
         rb.AddForce(new Vector2(-horizontalRecoil, 0));
         GameObject go = (GameObject)Instantiate(Projectile, horizontalShotPoint.position, horizontalShotPoint.rotation);
         go.GetComponent<Projectile>().xSpeed = xProjectileSpeed;
         go.GetComponent<Projectile>().ySpeed = 0f;
     } else {
         rb.AddForce(new Vector2(horizontalRecoil, 0));
         GameObject go = (GameObject)Instantiate(Projectile, horizontalShotPoint.position, horizontalShotPoint.rotation);
         go.GetComponent<Projectile>().xSpeed = -xProjectileSpeed;
         go.GetComponent<Projectile>().ySpeed = 0f;
     }
 }

 void VerticalShoot() { 
     rb.AddForce(new Vector2(0, verticalRecoil));
     GameObject go = (GameObject)Instantiate(Projectile, VerticalShotPoint.position, VerticalShotPoint.rotation);
     go.GetComponent<Projectile>().ySpeed = -yProjectileSpeed;
     go.GetComponent<Projectile>().xSpeed = 0f;
 }

}

public class Projectile : MonoBehaviour {

 [HideInInspector] public float xSpeed;
 [HideInInspector] public float ySpeed;

 public float lifeTime;
 public float distance;
 public LayerMask whatIsSolid;

 public GameObject destroyEffect;

 void Start() {
     Invoke("DestroyProjectile", lifeTime);
 }

 void Update() {
     RaycastHit2D hitInfo = Physics2D.Raycast(transform.position, transform.up, distance, whatIsSolid);
     if(hitInfo.collider != null) {
         if(hitInfo.collider.CompareTag("Ground")) {
             DestroyProjectile();
         }
     }

     Vector2 position = transform.position;
     position.x += xSpeed;
     position.y += ySpeed;
     transform.position = position;
 }

 void DestroyProjectile() {
     Instantiate(destroyEffect, transform.position, Quaternion.identity);
     Destroy(gameObject);
 }

}

these are a bullet code and a weapon code.

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

1 Reply

· Add your reply
  • Sort: 
avatar image
0
Best Answer

Answer by Llama_w_2Ls · Dec 27, 2020 at 10:03 AM

I believe your code is quite optimized in the Updates (no unnecessary object references or hefty processes), however, in your horizontalShoot() method, and VerticalShoot() method, you're wasting a few clock cycles 'getting' components and writing more code than you need to, which does add up, but not significantly. Here's what I would do for your horizontalShoot() method instead:

     void horizontalShoot()
     {
         GameObject go = (GameObject)Instantiate(Projectile, horizontalShotPoint.position, horizontalShotPoint.rotation);
         Projectile projectileScript = go.GetComponent<Projectile>();
 
         if (player.facingRight == true)
         {
             rb.AddForce(new Vector2(-horizontalRecoil, 0));
 
             projectileScript.xSpeed = xProjectileSpeed;
             projectileScript.ySpeed = 0f;
         }
         else
         {
             rb.AddForce(new Vector2(horizontalRecoil, 0));
             projectileScript.xSpeed = -xProjectileSpeed;
             projectileScript.ySpeed = 0f;
         }
     }

@coldfire1500

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 coldfire1500 · Dec 27, 2020 at 12:14 PM 0
Share

ohhh! thanks very much for your answer. I was worried about those 2 function and I'm glad the biggest problem is about instantiating the bullet twice. I though aswell about referencing bullet twice for the velocity but I guess thats not a problem.

avatar image Llama_w_2Ls coldfire1500 · Dec 27, 2020 at 12:22 PM 0
Share

It would be better if you did the same for VerticalShoot() as well.

avatar image coldfire1500 Llama_w_2Ls · Dec 27, 2020 at 03:53 PM 1
Share

DId the same to verticalShoot(); and moved stuff from update function to here as well void Update() { if(timeBtwShots <= 0) { if(Input.GetKey(KeyCode.DownArrow)) { xCanShoot = false; } else { xCanShoot = true; } if(Input.GetButtonDown("Fire1") && xCanShoot) { horizontalShoot(); timeBtwShots = horizontalStartTimeBtwShots; } else if (Input.GetKey(KeyCode.DownArrow) && Input.GetButtonDown("Fire1") && yCanShoot){ VerticalShoot(); timeBtwShots = VerticalStartTimeBtwShots; } } else { timeBtwShots -= Time.deltaTime; } }

     //void horizontalShoot() {
       
     void VerticalShoot() { 
         GameObject go = (GameObject)Instantiate(Projectile, VerticalShotPoint.position, VerticalShotPoint.rotation);
         Projectile projectileScript = go.GetComponent<Projectile>();
         CooldownBar.isntance.UseStamina(100);
         player.anim.SetBool("ShootDown", true);
 
         rb.AddForce(new Vector2(0, verticalRecoil));
         projectileScript.ySpeed = -yProjectileSpeed;
         projectileScript.xSpeed = 0f;
     }
 }
avatar image coldfire1500 · Dec 27, 2020 at 12:31 PM 0
Share

but I gues I can reference to the script bullet like that, realy cool

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

The best place to ask and answer questions about development with Unity.

To help users navigate the site we have posted a site navigation guide.

If you are a new user to Unity Answers, check out our FAQ for more information.

Make sure to check out our Knowledge Base for commonly asked Unity questions.

If you are a moderator, see our Moderator Guidelines page.

We are making improvements to UA, see the list of changes.



Follow this Question

Answers Answers and Comments

118 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

How to Make Character Shoot Where Aiming with Mouse 0 Answers

Ship won't shoot right in SMHUP. Help?? 2 Answers

velocity of bullet in rifile rotation 1 Answer

bullets are spawning under me and they don't move 1 Answer

Random Raycast inside crosshairs 1 Answer

  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges