Physics2D.OverlapCircle works / Physics2D.OverlapCircleNonAlloc does not work
It's as simple as the title says:
private Collider2D[] gravityColliders;
private void Awake() {
gravityColliders = new Collider2D[20];
}
public void FixedUpdate() {
// Does not work anymore
int collCount = Physics2D.OverlapCircleNonAlloc(transform.position, influenceRadius, gravityColliders, 1 << LayerMask.NameToLayer("Gravity"));
for (int i = 0; i < collCount; i++) {
Vector2 diff = transform.position - gravityColliders[i].transform.position;
gravityColliders[i].GetComponent<GravityReceiveBehaviour>().AddForce((diff.normalized * (gravity / (diff.magnitude * diff.magnitude))));
}
// for testing purpose: works ..
Collider2D c = Physics2D.OverlapCircle(transform.position, influenceRadius, 1 << LayerMask.NameToLayer("Gravity"));
if (c) {
Vector2 diff = transform.position - c.transform.position;
c.GetComponent<GravityReceiveBehaviour>().AddForce((diff.normalized * (gravity / (diff.magnitude * diff.magnitude))));
}
}
The collCount variable is always 0.
Had someone else this problem before? I am searching for hours now, but I can't find the problem. Every help is appreciated!
Felix
Answer by felixpk · May 02, 2017 at 10:47 AM
Finally I found the solution:
Since it is a base class that is inherited by some other class, the Awake() function was not called.
declaring awake like
public virtual void Awake(){ }
and calling it like
public override void Awake(){
base.Awake();
}
My fault was not checking whether the Array is correctly initialized or not.
Important: if you use Physics2D.OverlapCircleNonAlloc, there will be no Exception if the preallocated array isn't initialized!
Your answer
Follow this Question
Related Questions
Unity Overlap Point Causing Error 0 Answers
Ground Script explanation 1 Answer
OverlapBox not working as expected 0 Answers
Top-down collisiondetection 0 Answers