简体   繁体   中英

How to check for collision in an if statement in Unity 2D

I have a script that counts down from 20 to 0, then when it reaches 0 a boolean is set to true. What I want that boolean to do is write something on the console when the player is collided with the sprite the script is on, but I only want this to happen if it's true. Here's the code:

public float timeLeft = 10f;
public bool canHarvest;

public void Start()
{
    canHarvest = false;
}


public void Update()
{
    timeLeft -= Time.deltaTime;



    if (timeLeft < 0)
    {
        Debug.Log("IM READY TO HARVEST");
        canHarvest = true;

    }

    if (canHarvest = true)
    {
        public void OnTriggerEnter2D(Collider2D col)
        {
            if (col.gameObject.tag == "Player")
            {
                Debug.Log("true");
            }
        }
    }



}

}

What I want this code to do is set canHarvest to false at the start (meaning that if the player collides with the object the script is on nothing will happen), and once timeLeft reaches 0 it should set canHarvest to true, meaning that if the player collides with the object the script is on, the object the script is on will disappear. This is not working as I can't have the if statement checking if the player collides inside the if statement checking if canHarvest is true. Please help!

You should move the OnTriggerEnter2D definition outside the Update() method and conditional check should be inside the function:

public float timeLeft = 10f;
public bool canHarvest;

public void Start()
{
    canHarvest = false;
}

public void Update()
{
    timeLeft -= Time.deltaTime;

    if (timeLeft < 0)
    {
        Debug.Log("IM READY TO HARVEST");
        canHarvest = true;    
    }      
}

public void OnTriggerEnter2D(Collider2D col)
{
     if (canHarvest && col.gameObject.tag == "Player")
     {
         Debug.Log("true");
     }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM