Hello,

As a beginner, I’m stuck at some point.

I have a rigidbody2D object, at a given moment I want to check how many items are touching to that object.

Say I have a floor and lots of balls (it may be 10, it may be 100), I want to know how many of the balls are actually on the ground. Let’s say the floor is not necessarily flat, so checking the y-position won’t help.

Is there a property of that floor item to help with this, or should I check one by one with every other item.

You can use OnCollisionEnter, and a public integer variable attached to the floor object, for example:

GameObject floor;

void Update () {
floor = gameObject.Find("Floor");
}

void OnCollisionEnter2D (Collision2D col) {
if (col.name == "Floor"){
floor.GetComponent<BallCount>().balls ++;
}
}

void OnCollisionExit2D (Collision2D col){
if (col.name == "Floor"){
floor.GetComponent<BallCount>().balls --;
}
}

Then, add a script to the floor called BallCount:

int balls;

That’s it really. All the script attached to the floor needs to have is that integer value that stores the number of balls. I don’t use 2D often, so I may have typed an error in the collider methods.