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

Discussion Weapon pickup and drop in Hotline Miami Parody Game

Discussion in '2D' started by luckyfry00, Aug 4, 2023.

  1. luckyfry00


    Jul 1, 2023
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    5. public class PlayerAnimationController : MonoBehaviour
    6. {
    7.     Animator anim;
    8.     PlayerWeaponManager pw;
    9.     int weaponID = 0;
    11.     void Start()
    12.     {
    13.         anim = GetComponent<Animator>();
    14.         pw = GetComponent<PlayerWeaponManager>();
    15.     }
    17.     void Update()
    18.     {
    19.         WeaponAnimation(pw.curWeaponType);
    20.         anim.SetInteger("weapons", weaponID);
    21.     }
    23.     void WeaponAnimation(string weapon)
    24.     {
    25.         switch (weapon)
    26.         {
    27.             case "Nothing":
    28.                 weaponID = 0;
    29.                 break;
    30.             case "Gun":
    31.                 weaponID = 1;
    32.                 break;
    33.             case "Pistol":
    34.                 weaponID = 2;
    35.                 break;
    36.             default:
    37.                 break;
    38.         }
    39.     }
    40. }
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    5. public class PlayerWeaponManager : MonoBehaviour
    6. {
    7.     public string curWeaponType;
    8.     public bool inTrigger = false;
    9.     public float throwForce = 800.0f;
    10.     public float pickupDelay = 0.1f;
    11.     public float friction = 10.0f;
    12.     private List<Collider2D> itemColliders; // Список коллайдеров оружия в стэке
    14.     void Start()
    15.     {
    16.         itemColliders = new List<Collider2D>(); // Инициализируем список коллайдеров
    17.     }
    19.     void Update()
    20.     {
    21.         WeaponManager();
    22.     }
    24.     void WeaponManager()
    25.     {
    26.         if (Input.GetMouseButtonDown(1) && !inTrigger)
    27.         {
    28.             dropWeapon(curWeaponType);
    29.         }
    30.     }
    32.     public void dropWeapon(string weapon)
    33.     {
    34.         if (curWeaponType != "Nothing")
    35.         {
    36.             GameObject weaponPrefab = Resources.Load<GameObject>("Prefabs/Items/" + curWeaponType);
    37.             if (weaponPrefab != null)
    38.             {
    39.                 GameObject droppedWeapon = Instantiate(weaponPrefab, transform.position, Quaternion.identity);
    40.                 Rigidbody2D droppedWeaponRb = droppedWeapon.GetComponent<Rigidbody2D>();
    41.                 if (droppedWeaponRb != null)
    42.                 {
    43.                     Vector2 throwDirection = transform.right.normalized;
    44.                     droppedWeaponRb.AddForce(throwDirection * throwForce, ForceMode2D.Impulse);
    45.                     droppedWeaponRb.drag = friction;
    46.                 }
    47.                 curWeaponType = "Nothing";
    48.             }
    49.             else
    50.             {
    51.                 Debug.Log("Weapon prefab not found: " + curWeaponType);
    52.             }
    53.         }
    54.     }
    56.     // Метод для добавления коллайдера предмета в стэк
    57.     public void AddItemCollider(Collider2D itemCollider)
    58.     {
    59.         itemColliders.Add(itemCollider);
    60.         // Отключаем коллайдер предмета, чтобы его нельзя было сразу подобрать, если на него брошено другое оружие
    61.         itemCollider.enabled = false;
    62.     }
    64.     // Метод для удаления коллайдера предмета из стэка
    65.     public void RemoveItemCollider(Collider2D itemCollider)
    66.     {
    67.         itemColliders.Remove(itemCollider);
    68.         // Включаем коллайдер предмета, когда он находится сверху стэка и может быть подобран
    69.         itemCollider.enabled = true;
    70.     }
    71. }
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    5. [System.Serializable]
    6. public class Item
    7. {
    8.     public enum WeaponType //Список всего нашего оружия
    9.     {
    10.         Nothing, //0
    11.         Gun, //1
    12.         Pistol //2
    13.     }
    15.     public WeaponType weaponType;
    16. }
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    5. public class ItemManager : MonoBehaviour
    6. {
    7.     public Item item;
    8.     PlayerWeaponManager pw;
    9.     private Collider2D itemCollider; // Ссылка на коллайдер предмета
    11.     void Start()
    12.     {
    13.         pw = FindObjectOfType<PlayerWeaponManager>();
    14.         itemCollider = GetComponent<Collider2D>(); // Получаем коллайдер предмета
    15.     }
    17.     private void OnTriggerEnter2D(Collider2D col)
    18.     {
    19.         // Проверяем, если объект с тегом "Item" входит в триггер предмета, добавляем его коллайдер в список
    20.         if (col.CompareTag("Item"))
    21.         {
    22.             pw.AddItemCollider(col); // Передаем коллайдер предмета в PlayerWeaponManager
    23.         }
    24.     }
    26.     private void OnTriggerExit2D(Collider2D col)
    27.     {
    28.         if ( == "Player")
    29.         {
    30.             col.GetComponent<PlayerWeaponManager>().inTrigger = false;
    31.         }
    32.         // Если объект с тегом "Item" выходит из триггера предмета, удаляем его коллайдер из списка
    33.         if (col.CompareTag("Item"))
    34.         {
    35.             pw.RemoveItemCollider(col); // Удаляем коллайдер предмета из PlayerWeaponManager
    36.         }
    37.     }
    39.     private void OnTriggerStay2D(Collider2D col)
    40.     {
    41.         if ( == "Player")
    42.         {
    43.             col.GetComponent<PlayerWeaponManager>().inTrigger = true;
    45.             if (Input.GetMouseButtonDown(1))
    46.             {
    47.                 StartCoroutine("wait");
    48.             }
    49.         }
    50.     }
    52.     IEnumerator wait()
    53.     {
    54.         if (pw.curWeaponType != "Nothing")
    55.         {
    56.             pw.dropWeapon(pw.curWeaponType); //выкинули оружие
    57.         }
    58.         yield return new WaitForSeconds(0.05f); //подождали 0,05 сек
    59.         pw.curWeaponType = item.weaponType.ToString(); //заменили оружие в руке с выкинутого на поднятый, либо отсутствующий
    60.         Destroy(gameObject); //удалили объект, который подобрали
    61.     }
    62. }
    I only recently (a month ago) started to understand Unity, and decided to make a clone of the Hotline Miami game (or rather a parody). I managed to make a sight, the movement of the camera from the sight, the movement of the character.
    That's just huge problems arose with the selection and drop of weapons.
    The mechanics are as follows: There is a weapon on the floor, you approach it and pick it up (the object is destroyed, the variable of the weapon changes to the one that was picked up, the animation is played). This is done by clicking the RIGHT mouse button. If we want to throw an object, then we also press the RIGHT mouse button. If we already have a weapon in our hands, then the current one is dropped, and the lying one is picked up. There are several problems.
    1. Why the script is not executed immediately from the first right-click (namely selection).
    2. If two or more items (weapons) are together, then when trying to pick up one is taken, and the second simply disappears.
    A lot of attempts have been made to solve this problem. I've been tormenting ChatGPT for a very long time, I've been practicing Collider2D. It still doesn't work out.
    Scripts are attached:

    Attached Files:

    Last edited: Aug 4, 2023
  2. karderos


    Mar 28, 2023
    u should post the code normally ppl dont want to download files
  3. luckyfry00


    Jul 1, 2023
  4. MelvMay


    Unity Technologies

    May 24, 2013
    The physics callbacks happen at the end of the simulation step; the simulation happens (by default) during the FixedUpdate. FixedUpdate doesn't happen per-frame because of what it is.

    You should always read input per-frame, not during FixedUpdate. Asking if you pressed a mouse button this frame doesn't make sense in a callback that doesn't happen per-frame. GetMouseButtonDown, as its docs state, tell you if the mouse was pressed this frame and each frame it's cleared.

    You either store the mouse/key/touch state per-frame and then use that state in the callbacks or you run physics per-frame (but this has its own discussion beyond this topic).
  5. Kurt-Dekker


    Mar 16, 2013
    Why not work through three (3) different 2D weapon pickup / drop tutorials until you understand what is involved?

    Once you understand the basics, applying it to your specific needs should be easy.

    Imphenzia: How Did I Learn To Make Games:

    Tutorials and example code are great, but keep this in mind to maximize your success and minimize your frustration:

    How to do tutorials properly, two (2) simple steps to success:

    Step 1. Follow the tutorial and do every single step of the tutorial 100% precisely the way it is shown. Even the slightest deviation (even a single character!) generally ends in disaster. That's how software engineering works. Every step must be taken, every single letter must be spelled, capitalized, punctuated and spaced (or not spaced) properly, literally NOTHING can be omitted or skipped.

    Fortunately this is the easiest part to get right: Be a robot. Don't make any mistakes.

    If you get any errors, learn how to read the error code and fix your error. Google is your friend here. Do NOT continue until you fix your error. Your error will probably be somewhere near the parenthesis numbers (line and character position) in the file. It is almost CERTAINLY your typo causing the error, so look again and fix it.

    Step 2. Go back and work through every part of the tutorial again, and this time explain it to your doggie. See how I am doing that in my avatar picture? If you have no dog, explain it to your house plant. If you are unable to explain any part of it, STOP. DO NOT PROCEED. Now go learn how that part works. Read the documentation on the functions involved. Go back to the tutorial and try to figure out WHY they did that. This is the part that takes a LOT of time when you are new. It might take days or weeks to work through a single 5-minute tutorial. Stick with it. You will learn.

    Step 2 is the part everybody seems to miss. Without Step 2 you are simply a code-typing monkey and outside of the specific tutorial you did, you will be completely lost. If you want to learn, you MUST do Step 2.

    Of course, all this presupposes no errors in the tutorial. For certain tutorial makers (like Unity, Brackeys, Imphenzia, Sebastian Lague) this is usually the case. For some other less-well-known content creators, this is less true. Read the comments on the video: did anyone have issues like you did? If there's an error, you will NEVER be the first guy to find it.

    Beyond that, Step 3, 4, 5 and 6 become easy because you already understand!

    Finally, when you have errors, don't post here... just go fix your errors! Here's how:

    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.

    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.

    Look in the documentation. Every API you attempt to use is probably documented somewhere. Are you using it correctly? Are you spelling it correctly?

    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.