Home > Back-end >  OnCollisionEnter for only one object with same script
OnCollisionEnter for only one object with same script

Time:06-22

The problem is that - when two objects with the same scripts collide, I need to destroy them and create a new object. But they collide eachother and instead of one final object,i have 2 of them.

private void OnCollisionEnter2D(Collision2D collision)
{
    var drop = collision.gameObject.GetComponent<DropBase>();
    if (drop != null)
    {
        Destroy(collision.gameObject);
        Instantiate(_pile, transform.position, Quaternion.identity);
        Destroy(gameObject);
    }
}

I was trying give every of object lifetime,and the longer living object have rights to create new one,but i have situation where thay created at same time,and this method doesn't work.

CodePudding user response:

You can try to notify another object that the collision is already processed. It can be done in different ways, here is one of them:

public bool IsPileInstantiated { get; private set; } 

void Awake()
{
    IsPileInstantiated = false;
}

private void OnCollisionEnter2D(Collision2D collision)
{
    var drop = collision.gameObject.GetComponent<DropBase>();
    if (drop != null)
    {
        if(drop.IsPileInstantiated == false)
        {
            Instantiate(_pile, transform.position, Quaternion.identity);
            this.IsPileInstantiated = true;
        }
        Destroy(gameObject);
    }
}

Perhaps it even has the sense to move this logic out of your drop objects. For example, notify another object (some GameManager or something like that) about a collision, and that object will have events from both objects, can filter these events, destroy objects if needed and create a needed object if it is needed.

CodePudding user response:

You can deactive the two game objects before destroying them, then you can ignore the collision if one of the game object is inactive.

private void OnCollisionEnter2D(Collision2D collision)
{
    var incomingGameObject = collision.gameObject;
    if(!gameObject.activeSelf || !incomingGameObject.activeSelf)
        return;

    var drop = incomingGameObject.GetComponent<DropBase>();
    if (drop != null)
    {
        incomingGameObject.SetActive(false);
        Destroy(incomingGameObject);
        Instantiate(_pile, transform.position, Quaternion.identity);
        gameObject.SetActive(false);
        Destroy(gameObject);
    }
}
  • Related