How to destroy my cannon balls when they come in contact with the anything.

So the cannonballs are just passing through the wall, but when the player comes they are destroyed, but if player comes in contact they get destroyed. Here is the script :-

void OnCollisionEnter2D(Collision2D collision)
    {
       Destroy(gameObject);
    }

And both the wall and Player have collider.

it needs a rigidbody, at least one of them (wall or cannon ball).

Incase the other solution is not working, what you can do is have a variable Vector3 previousPosition; in your c# script and then have this as update:

void Update()
{
    Vector3 direction = (transform.position - previousPosition).normalized;
    float distance = Vector3.Distance(transform.position, previousPosition);

    RaycastHit2D hit = Physics2D.Raycast(previousPosition, direction, distance);
    if(hit.transform.gameObject != gameObject) {
        Destroy(gameObject);
    }
    previousPosition = transform.position;
}

And then in Start() define previousPosition as transform.position with previousPosition = transform.position;
I am not 100% sure that this will work for you, but I recommend trying it.