Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • 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 /
  • Help Room /
avatar image
0
Question by Impz · Oct 09, 2016 at 06:58 PM · 2dshootingreloading

Having trouble shooting and reloading

     public float fireRate = 0;
     public float basicDamage = 0;
     public LayerMask whatToHit;
 
     float timeToFire = 0;
     Transform firePoint;
 
     //reloading Variables
     private var reloadTime = 2;
 
     public float clipAmmo = 50;
     public float clipSize = 50;
     public float stockAmmo = 100; 
 
     // Use this for initialization
     void Awake () {
         firePoint = transform.FindChild("FirePoint");
         if (firePoint == null)
         {
             Debug.LogError("No firepoint dumbass.");
         }
     }
 
     IEnumerator Reload()
     {
         if (clipAmmo <= 0)
         {
             yield return new WaitForSeconds(reloadTime);
             clipAmmo = 50;
         }
         Reload();
     }
 
 // Update is called once per frame
 void Update () {
         
         if (fireRate == 0)
         {
             if (Input.GetButtonDown ("Fire1"))
             {
                 Shoot();
             }
         }
         else
         {
             if (Input.GetButtonDown ("Fire1") && timeToFire.time > timeToFire)
             {
                 timeToFire = timeToFire.time + 1 / fireRate;
                 Shoot();
             }
         }
     }
 
        void Shoot () {
         Vector2 mousePosition = new Vector2(Camera.main.ScreenToWorldPoint(Input.mousePosition).x, camera.main.ScreenToWorldPoint(Input.mousePosition).y);
         Vector2 firePointPosition = new Vector2(firePoint.position.x, firePoint.position.y);
         RaycastHit2D hit = Physics2D.Raycast(firePointPosition, mousePosition, mousePosition-firePointPosition, 100, whatToHit);
         if (hit.collider != null)
         {
             Destroy(gameObject);
         }
     }
 
     void Reload()
     {
         if (Input.GetButtonDown("Reload"))
         {
             yield WaitForSeconds (reloadTime);
             clipAmmo = 50;
         }
     }
 }

Currently what I'm dealing with. I have 11 Errors. Is there any way I can simplify this code? I'm fairly new to C# (less than 6 months experience).

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
1
Best Answer

Answer by AlbinoStoic · Oct 09, 2016 at 08:12 PM

Hey there!

It helps to rewrite code in a meaningful (readable) way, consider:

 // required for IEnuemrator
 using System.Collections;

 using UnityEngine;

 public class Test : MonoBehaviour
 {
     // Use meaningful TitleCase variables for public things!
     public float BaseDamage = 0f;
     public float FireRate = .5f; // means twice per second, lower number is faster
     public float ReloadTime = 2f;

     public LayerMask ValidTargets;

     // Put all public variables first, it's easier to read.
     public int ClipContents = 20;
     public int ClipCapacity = 20;
     public int Stock = 40;

     // Private variables get camelCase
     private float fireDelay = 0f;
     private Transform firePoint;

     // Putting stuff inside a `region` block is optional, but cleans up files
     #region Unity
     private void Awake()
     {
         // Unity is pretty smart about this, and will throw an error anyways
         // You don't have to have your own error checking for assignment.
         firePoint = transform.Find("firePoint");
     }
     
     // We implement the fireDelay counter in FixedUpdate so it's run exactly 20 times a second
     private void FixedUpdate()
     {
         // The delay value reduces towards 0 over time
         if (fireDelay > 0)
             fireDelay--;
     }

     // Whereas things inside Update are tied to your FRAME RATE
     private void Update()
     {
         // When fireDelay reaches 0, we can fire again.
         if (fireDelay <= 0)
             if (Input.GetButtonDown("Fire1"))
             {
                 // Reset fireDelay when we fire
                 fireDelay = FireRate * 20f;
                 Shoot();
             }
         
         if (Input.GetButtonDown("Reload"))
         {
             // Prevent firing for at least reloadTime
             fireDelay = ReloadTime * 20f;

             // Call the reload IEnumerator
             StartCoroutine(Reload());
         }
     }
     #endregion

     private IEnumerator Reload()
     {
         // Until our clip is full, use bullets to fill it.
         while (ClipContents < ClipCapacity)
         {
             // We ran out of bullets to reload
             // yield break cancels an IEnumerator entirely
             if (Stock == 0) yield break;

             ClipContents++;
             Stock--;

             // This lets us reload 20 bullets per second
             yield return new WaitForFixedUpdate();
         }

         // IEnumerator must `yield return null` at the end.
         yield return null;
     }

     private void Shoot()
     {
         // Make sure our clip isn't empty
         if (ClipContents == 0)
         {
             // This is where you might add a "firingEmpty" sound
             return;
         }

         // Unity expresses things in 3D even if you're not..
         Vector2 point = new Vector2(Input.mousePosition.x, Input.mousePosition.y); // Are you sure it's not z ?

         // Check where that is in world position
         point = Camera.main.ScreenToWorldPoint(point);

         Vector2 reticlePos = new Vector2(firePoint.position.x, firePoint.position.y); // are you sure it's not z ?

         // "Fire the bullet" beyond this point
         // Consider actually spawning a bullet prefab
         // - then you can check collision on the bullet
         ClipContents--;

         // Arguments are "origin", "direction", "distance" and "layerMask" in that order
         RaycastHit2D hit = Physics2D.Raycast(reticlePos, point - reticlePos, 100, ValidTargets);
         
         if (hit.collider != null && hit.transform != null)
             // I'm assuming you meant to destroy the target, not yourself
             Destroy(hit.transform.gameObject);
     }
 }
Comment
Add comment · 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

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.

Follow this Question

Answers Answers and Comments

110 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

Related Questions

2D game how to make my enemy can evade the laser of my player 0 Answers

,how to Instantiate a bullet up when firePoint of the character goes up 0 Answers

No overload for method 'fireBullet' takes 0 arguments 1 Answer

Character Shooting Mechanic 2D Issues 0 Answers

How do I get my character to shoot towards my mouse in a 2D top down? 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