Weapon pickup and drop in Hotline Miami Parody Game

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerAnimationController : MonoBehaviour
{
    Animator anim;
    PlayerWeaponManager pw;
    int weaponID = 0;

    void Start()
    {
        anim = GetComponent<Animator>();
        pw = GetComponent<PlayerWeaponManager>();
    }

    void Update()
    {
        WeaponAnimation(pw.curWeaponType);
        anim.SetInteger("weapons", weaponID);
    }

    void WeaponAnimation(string weapon)
    {
        switch (weapon)
        {
            case "Nothing":
                weaponID = 0;
                break;
            case "Gun":
                weaponID = 1;
                break;
            case "Pistol":
                weaponID = 2;
                break;
            default:
                break;
        }
    }
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerWeaponManager : MonoBehaviour
{
    public string curWeaponType;
    public bool inTrigger = false;
    public float throwForce = 800.0f;
    public float pickupDelay = 0.1f;
    public float friction = 10.0f;
    private List<Collider2D> itemColliders; // Список коллайдеров оружия в стэке

    void Start()
    {
        itemColliders = new List<Collider2D>(); // Инициализируем список коллайдеров
    }

    void Update()
    {
        WeaponManager();
    }

    void WeaponManager()
    {
        if (Input.GetMouseButtonDown(1) && !inTrigger)
        {
            dropWeapon(curWeaponType);
        }
    }

    public void dropWeapon(string weapon)
    {
        if (curWeaponType != "Nothing")
        {
            GameObject weaponPrefab = Resources.Load<GameObject>("Prefabs/Items/" + curWeaponType);
            if (weaponPrefab != null)
            {
                GameObject droppedWeapon = Instantiate(weaponPrefab, transform.position, Quaternion.identity);
                Rigidbody2D droppedWeaponRb = droppedWeapon.GetComponent<Rigidbody2D>();
                if (droppedWeaponRb != null)
                {
                    Vector2 throwDirection = transform.right.normalized;
                    droppedWeaponRb.AddForce(throwDirection * throwForce, ForceMode2D.Impulse);
                    droppedWeaponRb.drag = friction;
                }
                curWeaponType = "Nothing";
            }
            else
            {
                Debug.Log("Weapon prefab not found: " + curWeaponType);
            }
        }
    }

    // Метод для добавления коллайдера предмета в стэк
    public void AddItemCollider(Collider2D itemCollider)
    {
        itemColliders.Add(itemCollider);
        // Отключаем коллайдер предмета, чтобы его нельзя было сразу подобрать, если на него брошено другое оружие
        itemCollider.enabled = false;
    }

    // Метод для удаления коллайдера предмета из стэка
    public void RemoveItemCollider(Collider2D itemCollider)
    {
        itemColliders.Remove(itemCollider);
        // Включаем коллайдер предмета, когда он находится сверху стэка и может быть подобран
        itemCollider.enabled = true;
    }
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[System.Serializable]
public class Item
{
    public enum WeaponType //Список всего нашего оружия
    {
        Nothing, //0
        Gun, //1
        Pistol //2
    }

    public WeaponType weaponType;
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ItemManager : MonoBehaviour
{
    public Item item;
    PlayerWeaponManager pw;
    private Collider2D itemCollider; // Ссылка на коллайдер предмета

    void Start()
    {
        pw = FindObjectOfType<PlayerWeaponManager>();
        itemCollider = GetComponent<Collider2D>(); // Получаем коллайдер предмета
    }

    private void OnTriggerEnter2D(Collider2D col)
    {
        // Проверяем, если объект с тегом "Item" входит в триггер предмета, добавляем его коллайдер в список
        if (col.CompareTag("Item"))
        {
            pw.AddItemCollider(col); // Передаем коллайдер предмета в PlayerWeaponManager
        }
    }

    private void OnTriggerExit2D(Collider2D col)
    {
        if (col.name == "Player")
        {
            col.GetComponent<PlayerWeaponManager>().inTrigger = false;
        }
        // Если объект с тегом "Item" выходит из триггера предмета, удаляем его коллайдер из списка
        if (col.CompareTag("Item"))
        {
            pw.RemoveItemCollider(col); // Удаляем коллайдер предмета из PlayerWeaponManager
        }
    }

    private void OnTriggerStay2D(Collider2D col)
    {
        if (col.name == "Player")
        {
            col.GetComponent<PlayerWeaponManager>().inTrigger = true;

            if (Input.GetMouseButtonDown(1))
            {
                StartCoroutine("wait");
            }
        }
    }

    IEnumerator wait()
    {
        if (pw.curWeaponType != "Nothing")
        {
            pw.dropWeapon(pw.curWeaponType); //выкинули оружие
        }
        yield return new WaitForSeconds(0.05f); //подождали 0,05 сек
        pw.curWeaponType = item.weaponType.ToString(); //заменили оружие в руке с выкинутого на поднятый, либо отсутствующий
        Destroy(gameObject); //удалили объект, который подобрали
    }
}

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:

9194039–1281533–PlayerAnimationController.cs (868 Bytes)
9194039–1281536–PlayerWeaponManager.cs (2.3 KB)
9194039–1281539–Item.cs (298 Bytes)
9194039–1281542–ItemManager.cs (2.25 KB)

u should post the code normally ppl dont want to download files

Done.

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).

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.
BE PERFECT IN EVERYTHING YOU DO HERE!!

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.