Home > Back-end >  want to pick up tools or guns but want to pick only one at a time in unity c#
want to pick up tools or guns but want to pick only one at a time in unity c#

Time:10-27

want to pick up only one gun at a time but the player is picking both guns when I press the button so someone please solve this issue I want to pick up only one gun when the player presses a particular key but when the player drops the gun down then the only player can pick another gun

public void pickup() //this is a function when player presses to pick up guns 
{
    if (Input.GetKeyDown(KeyCode.E) && Vector3.Distance(s.transform.position, transform.position) <=  5  && dontpickup)
    {
        //var a = gameObject.FindWithTag("player");
        transform.SetParent(s);
        Vector3 temp = transform.position;
        temp.x = player.transform.position.x;
        temp.y = player.transform.position.y;
        transform.position = temp   new Vector3(4, 0, 0);
        Rigidbody2D rb = GetComponent<Rigidbody2D>();
        rb.isKinematic = true;
        Collider2D c = GetComponent<Collider2D>();
        c.isTrigger = true;
        needdropdown = true;
    }
}

public void dropdown() //this is a function when player presses to drop down the guns
{
    if (Input.GetKeyDown(KeyCode.Q) && needdropdown)
    {
        //var a = gameObject.FindWithTag("player");
        transform.SetParent(null);
        
        Rigidbody2D rb = GetComponent<Rigidbody2D>();
        rb.isKinematic = false;
        Collider2D c = GetComponent<Collider2D>();
        c.isTrigger = false;
    }
}

void OnTriggerStay2D(Collider2D trig)
{
    if(f.gameObject != null && gameObject.tag == "player")
    {
        dontpickup = true;
    }
}

CodePudding user response:

You can add variable, something like _gunPickedUpTimeStamp. When player picks up gun assign value DateTime.Now. And add condition that is evaluated every time when player picks up some gun. Something like

if ((_gunPickedUpTimeStamp - DateTime.Now) > TimeSpan.FromSeconds(5)) {
   do something...
  _gunPickedUpTimeStamp = DateTime.Now
}

CodePudding user response:

I guess you should modify the value of dontpickup in these two methods:

    public void pickup() //this is a function when player presses to pick up guns 
    {
        if (Input.GetKeyDown(KeyCode.E) && Vector3.Distance(s.transform.position, transform.position) <=  5  && dontpickup)
        {
            //before code
            needdropdown = true;
            dontpickup = false;
            
        }
    }
    
    public void dropdown() //this is a function when player presses to drop down the guns
    {
        if (Input.GetKeyDown(KeyCode.Q) && needdropdown)
        {
            //before code
            needdropdown = false;
            dontpickup = true;
        }
    }
  • Related