How do i make an object to be visible only on a particular layer?

Please refer the image below to understand.

I am working on 2D game. I have three elements: "background(layer 0), foreground(layer 1) and the object".

I have used sprite renderer to set background and foreground images. Object gets instantiated during runtime.

How do i make Part-A of the object invisible? I want to make object visible only on foreground. If the object is completely on the background, it should be completely invisible. if the object is completely on foreground, it should be completely visible. Part-A and Part-B are just for reference. It is one single object.

The goal to be achieved is the image below:

via editor or via script change sorting order in the SpriteRenderer as follows:
GetComponent<SpriteRenderer>().sortingOrder