Keeping track of number of contacts per collision in C#

Hello C# masters,

What I want to be able to do is keep count of the number of contacts that exist for each Collision whilst each Collision exists. So that in OnCollisionStay I can just check to see if that particular Collision has more or less contacts than it did previously. Put specifically, i need a way to associate a particular value with its corresponding Collision instance, from one frame to the next.

My C# is not good enough yet to know the best way to go about this. Should I use multi-type arrays? Create a class to hold each one? A little example code would be greatly appreciated.

Thanks for your help.

Interesting question – I’m going to mark this for notifications to see what other responses are posted.

Since we’re looking at C#, and I’m assuming you’re coding to 2.1, how about a generic List and on trips through OnCollisionStay do your Contains, Add, Remove, etc for the Collision being evaluated (this is off the cuff and untested, so if it sucketh, sorrrrry)

// init list and bool to avoid race conditions

List<Collision> storedCollisions = new List<Collision>();

bool removingStoredCollision = false;

void OnCollisionStay(Collision collision)
{
    while(removingStoredCollision){}

    if(storedCollisions.Contains(collision))
    {
        // evaluate .contacts.Length and do
        // whatever
    }
    else
    {
         storedCollisions.Add(collision);
    }
}

void OnCollisionExit(Collision collision)
{
    if(storedCollisions.Contains(collision))
    {
         removingStoredCollision = true;
         storedCollisions.Remove(collision);
         removingStoredCollision = false;        
    }
}

There are obviously several ways to do this, and I’m interested to see what other C# gurus have to offer. The race condition checking may also be unnecessary; I’m not 100% sure on the sequencing of Enter, Stay, Exit methods like Update and LateUpdate work (and removing an object from a Collection while it’s being enumerated is no good).

Also, from a memory standpoint we’re keeping track of the entire set of Collision objects when really all need is an int[,] of GetInstanceID’s and contact points.

This post is a tad dated, but offers a decent overview of available data structures: Unity Coding: Arrays, Hashtables and Dictionaries explained | robotduck