This was originally a post on unity's "unity answers" but the moderators are taking their sweet time approving it, so I'm posting it here on the far superior stack overflow cheer... so keep in mind this is a Unity engine issue in C# script... obviously...
So I'm trying to make a simple script to keep track of all the 2D colliders touching a certain 2D trigger collider. It's supposed to maintain a generic public 2D collider list of all the 2D colliders that were touching its 2D collider the current frame that can be accessed by other scripts to do other things. I've tried several implementations and have found that due to the order of events unity executes things in, that it's harder than it seems (for me anyway). The other scripts using the collider list from the sensor script only access the list during their update(), and logically it looks like the list should be properly populated at that time, but I must be wrong because it clearly isn't. Here's my most recent and best attempt, can someone tell me where I'm going wrong? (There's also a bool to ensure only new colliders are added, that part is irrelevant to what I'm asking... I think so anyway...)
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class SimpleColliderSensor : MonoBehaviour {
public bool repeatsallowed;
public List<Collider2D> sensedobjs;
bool clearlist;
public void init()
{
clearlist = false;
repeatsallowed = false;
sensedobjs = new List<Collider2D>();
}
void FixedUpdate()
{
}
void Update()
{
}
void LateUpdate()
{
clearlist = true;
}
void OnTriggerEnter2D(Collider2D c)
{
OnTriggerStay2D(c);
}
void OnTriggerStay2D(Collider2D c)
{
if (clearlist)
{
sensedobjs.Clear();
clearlist = false;
}
if (repeatsallowed)
{
sensedobjs.Add(c);
}
else
{
if (!sensedobjs.Contains(c))
{
sensedobjs.Add(c);
}
}
}
void OnCollisionStay2D(Collision2D c)
{
OnTriggerStay2D(c.collider);
}
void OnCollisionEnter2D(Collision2D c)
{
OnTriggerStay2D(c.collider);
}
}
it seems "clearlist" could just be set in update and it would work the same, but I was trying different things so it's in lateupdate now. Anyway, the list is often missing colliders it should be colliding with, but has some colliders. And yes, the sensor and sensee colliders are set to collide in the physics 2D project settings. I should probably mention that. I'd appreciate any insight anyone may have. Sorry so verbose. Thanks.