Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Bug error while making shotgun

Discussion in 'Scripting' started by MrThunderboi, Oct 9, 2022.

  1. MrThunderboi

    MrThunderboi

    Joined:
    Aug 26, 2022
    Posts:
    14
    Hello fellow coders I have attempted to code a shotgun script that shoots multiple bullets but I'm a beginner per say. So I went wrong with the randomness, I think and got and error "Non-invocable member 'Vector3.normalized' cannot be used like a method". Any help will be appreciated and ill get back to you.
    Code:
    ------------------------------------------------------------------------------------------------------------------------------------------------
    Code (csharp):
    1.  
    2. using System.Collections;
    3. using UnityEngine;
    4. using UnityEngine.UI;
    5. using TMPro;
    6. using Random = UnityEngine.Random;
    7. public class ShotGun : MonoBehaviour
    8. {
    9.  public float damage = 10f;
    10.  public float range = 100f;
    11.  public float fireRate = 1f;
    12.  public TextMeshProUGUI ammoDisplay;
    13.  public ParticleSystem muzzleFlash;
    14.  public GameObject impactEffect;
    15.  
    16.  
    17.  public int maxAmmo = 10;
    18.  public int currentAmmo;
    19.  public float reloadTime = 1f;
    20.  private bool isReloading = false;
    21.  int amountOfProjectiles = 17;
    22.  
    23.  
    24.  
    25.  public Animator animator;
    26.  
    27.  
    28.  
    29.  
    30.  public Camera fpsCam;
    31.  
    32.     void Start()
    33.     {
    34.         currentAmmo = maxAmmo;
    35.     }
    36.  
    37.  
    38.  
    39.  
    40.  private float nextTimeToFire = 0f;
    41.  
    42.  
    43.          
    44.     // Update is called once per frame
    45.     void Update()
    46.     {
    47.  
    48.     if (isReloading)
    49.         return;
    50.  
    51.     ammoDisplay.text = currentAmmo.ToString() + "/" + maxAmmo;
    52.  
    53.  
    54.     if (currentAmmo <= 0)
    55.     {
    56.      
    57.         StartCoroutine(Reload());
    58.         return;
    59.      
    60.     }
    61.         if (Input.GetKeyDown(KeyCode.R) && currentAmmo < maxAmmo)
    62.  
    63.          {
    64.  
    65.               StartCoroutine(Reload());
    66.  
    67.          }
    68.  
    69.  
    70.  
    71.  
    72.       if (Input.GetMouseButton(0) && Time.time >= nextTimeToFire)
    73.       {
    74.     nextTimeToFire = Time.time + 1f/fireRate;
    75.  
    76.     for(int i = 0; i < amountOfProjectiles; i++)
    77.         {
    78.             shoot();
    79.         }
    80.       }
    81.     }
    82.     IEnumerator Reload ()
    83.     {
    84.         isReloading = true;
    85.         Debug.Log("Reloading...");
    86.  
    87.         animator.SetBool("Reloading", true);
    88.  
    89.         yield return new WaitForSeconds(reloadTime - .25f);
    90.         animator.SetBool("Reloading", false);
    91.         yield return new WaitForSeconds(.25f);
    92.  
    93.         currentAmmo = maxAmmo;
    94.         isReloading = false;
    95.     }
    96.  
    97.  
    98.  
    99.  void shoot()
    100.  {
    101.  
    102.     muzzleFlash.Play();
    103.     currentAmmo--;
    104.  
    105.  
    106.     Vector3 direction = fpsCam.transform.forward;
    107.     Vector3 spread = Vector3.zero;
    108.     spread+= fpsCam.transform.up * Random.Range(-1f, 1f);
    109.     spread+= fpsCam.transform.right * Random.Range(-1f, 1f);
    110.     direction += spread.normalized() * Random.Range(0f, 0.2f);
    111.     RaycastHit hit;
    112.         if (Physics.Raycast(fpsCam.transform.position, fpsCam.transform.forward, out hit, range))
    113.     {
    114.         Debug.Log(hit.transform.name);
    115.         Target target = hit.transform.GetComponent<Target>();
    116.         Button button = hit.transform.GetComponent<Button>();
    117.         if (target != null)
    118.         {
    119.             target.TakeDamage(damage);
    120.         }
    121.         if (button != null)
    122.         {
    123.             button.TakeDamageButton(damage);
    124.         }
    125.      
    126.  
    127.  
    128.     }
    129.         GameObject impactGO = Instantiate(impactEffect, hit.point, Quaternion.LookRotation(hit.normal));
    130.         Destroy(impactGO, 2f);
    131.  
    132.  }
    133.  
    134.  
    135.  
    136.  
    137. }
    138. love, MrThunderboi
    139.  
     
    Last edited: Oct 9, 2022
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,947
    Sounds like typing mistakes to me! Go fix 'em!

    Seems like this is the THIRD time you have been reminded to format your code. Are you struggling with that simple step?

    How to use code tags: https://forum.unity.com/threads/using-code-tags-properly.143875/

    The complete error message contains everything you need to know to fix the error yourself.

    The important parts of the error message are:

    - the description of the error itself (google this; you are NEVER the first one!)
    - the file it occurred in (critical!)
    - the line number and character position (the two numbers in parentheses)
    - also possibly useful is the stack trace (all the lines of text in the lower console window)

    Always start with the FIRST error in the console window, as sometimes that error causes or compounds some or all of the subsequent errors. Often the error will be immediately prior to the indicated line, so make sure to check there as well.

    All of that information is in the actual error message and you must pay attention to it. Learn how to identify it instantly so you don't have to stop your progress and fiddle around with the forum.

    Remember: NOBODY here memorizes error codes. That's not a thing. The error code is absolutely the least useful part of the error. It serves no purpose at all. Forget the error code. Put it out of your mind.

    For actual problems, if you post a code snippet, ALWAYS USE CODE TAGS:

    How to use code tags: https://forum.unity.com/threads/using-code-tags-properly.143875/

    You may edit your post above.

    And as always, save yourself some time with these simple steps:

    How to report your problem productively in the Unity3D forums:

    http://plbm.com/?p=220

    This is the bare minimum of information to report:

    - what you want
    - what you tried
    - what you expected to happen
    - what actually happened, especially any errors you see
    - links to documentation you used to cross-check your work (CRITICAL!!!)
     
  3. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    10,620
    Whilst the love is appreciated, I think it's about time you start using code-tags because you've been asked now several times. Please start using them, also edit your post above to include them. Also, please don't mark this as a bug, it's not a bug, it's a compiler error where you're simply not typing code correctly. :)

    So you are simply making typos then asking how to fix them on the forums. The error tells you exactly where the problem is, you don't even mention where on your post. All you have to do is look at that part of your code.

    It would take you a moment to look at the scripting docs. There you'd see this:
    https://docs.unity3d.com/ScriptReference/Vector3-normalized.html

    You use it like this:
    Code (CSharp):
    1. spread.normalized()
    This doesn't look liked a method does it? No, it's a property. It doesn't use "()".
     
    All_American likes this.
  4. Homicide

    Homicide

    Joined:
    Oct 11, 2012
    Posts:
    656
    Don't think i have seen any actual Unity peoples as active on the forums as you have been lately Melv. Good stuff. But uhh...
    ? :D
     
  5. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    10,620
    I must've sneezed at the time of typing. Corrected. :D
     
  6. MrThunderboi

    MrThunderboi

    Joined:
    Aug 26, 2022
    Posts:
    14
    hi MelvMay sorry to bother you but I did put spread.Normalize() and it worked but I'm getting an error... again maybe you could check it out...? "Operator '*' cannot be applied to operands of type 'void' and 'float'" I think it has something to do with the multiply but I don't know what to put but I think everything else is still fine:D
    Code (csharp):
    1.  
    2. Vector3 direction = fpsCam.transform.forward;
    3.     Vector3 spread = Vector3.zero;
    4.     spread+= fpsCam.transform.up * Random.Range(-1f, 1f);
    5.     spread+= fpsCam.transform.right * Random.Range(-1f, 1f);
    6.     direction += spread.Normalize() * Random.Range(0f, 0.2f);
    7.  
    here's the error spot and I'm truly sorry for being a dunce:oops:
     
  7. orionsyndrome

    orionsyndrome

    Joined:
    May 4, 2014
    Posts:
    3,043
    The variant of the
    Normalize
    method that you're using doesn't return anything, that's what void means. It returns void. What is interesting with this case is that the docs are utterly misleading.
    Normalize
    method has two overloads, one is static (and takes an argument; covered by the docs), the other is instance-based (and has no arguments; this is what you used, but it's completely ignored by the docs).

    You rarely want to use
    Normalize
    method anyway and probably wanted to use normalized property instead, like so
    Code (csharp):
    1. direction += spread.normalized * Random.Range(0f, 0.2f);
    edit:
    You want to use
    Normalize
    only when you know what you're doing. The instance-based and the static methods will change the vector in place (meaning it will persistently change the vector).
    normalized
    functions differently, i.e. you apply it to a vector and get a new, normalized one in return, without changing anything.
    Code (csharp):
    1. // safe behavior
    2. var nv = vec.normalized; // nothing happens to vec
    Code (csharp):
    1. // both of these modify vec forever
    2. vec.Normalize(); // this doesn't return anything
    3. var nv = Vector3.Normalize(vec);
    edit2:
    it's somewhat confusing, but at least the docs are clear on this with the static variant.
     
    Last edited: Oct 11, 2022
  8. MrThunderboi

    MrThunderboi

    Joined:
    Aug 26, 2022
    Posts:
    14
    Man this is confusing and I'm using both but if I use normalized I'm back to the reason I posted this thread and get another error. By the way do you work for unity??
     
  9. orionsyndrome

    orionsyndrome

    Joined:
    May 4, 2014
    Posts:
    3,043
    Have you thought about taking a step back, just a little, to try and get a good grasp on what works and how?

    I mean what you're doing right now is the proper way to learn, don't get me wrong, but maybe you can follow some good tutorials first, and slowly get a feel for what's expected of you, both c-sharp- and Unity-wise.

    I agree that this situation with the docs isn't the best one, but if you only consider that it took me 5-10 minutes to explain this mistake to you, and only a couple of seconds to notice it, learning what is expected and why really pays off.

    No.
     
    Kurt-Dekker likes this.
  10. MrThunderboi

    MrThunderboi

    Joined:
    Aug 26, 2022
    Posts:
    14
    Alr I’ll step off the shotgun project
     
  11. orionsyndrome

    orionsyndrome

    Joined:
    May 4, 2014
    Posts:
    3,043
    Feel free to ask direct and concrete questions along the lines of "what this does" or "how do I achieve this or that" at any point in time. Of course you're free to ask whatever you want on this forum (as long as you follow the rules), but for such questions in particular I will always find time, which usually isn't the case with "I've got a null error", "pls halp" and "fix this". I think nobody likes those.
     
    angrypenguin, MelvMay and Kurt-Dekker like this.
  12. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    10,620
    Also, while you're studying stuff, note that in the simple cases of types like Vector2/Vector3 etc you can see the source implementation. This can help demystify what's going on in some cases; here's Vector3.
     
    AnimalMan likes this.
  13. MrThunderboi

    MrThunderboi

    Joined:
    Aug 26, 2022
    Posts:
    14
    Ok thank you and by the way does Unitys code sometimes change for updates??
     
  14. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    10,620
    Sorry, I don't understand what you're asking. It wouldn't be an update if Unity didn't change. APIs change yes therefore their implementation.

    You can see the script reference here where you can select the specific version of Unity at the top-left so see if an API was added/removed/present etc.
     
  15. MrThunderboi

    MrThunderboi

    Joined:
    Aug 26, 2022
    Posts:
    14
    Thank you melv and orionsyndrome for taking your time on me.:)