- Home /
Can't create an Collider2D array?
I have been trying to create an array of collider2D so i can disable all the respective colliders of an children's object.
But this error pops-up and i have tried to figured out what's wrong but nothing seems wrong to me, or I'm not seeing it.
ERROR: Cannot implicitly convert type UnityEngine.Collider2D' to
UnityEngine.Collider2D[]'
What I'm I doing wrong?
private Collider2D[] childrenColliders;
private bool destroied= false;
void Update (){
if (assetHitPoints<=0 && destroied == false){
Destroy();
}
}
void Destroy (){
Debug.Log("Destroying");
childrenColliders = GetComponentInChildren<Collider2D>();
foreach (Collider2D colliders in childrenColliders){
colliders.enabled = false;
}
particleSystem.Play();
destroied=true;
}
Answer by Bentley · Jan 21, 2015 at 06:21 PM
You are getting that error because GetComponentInChildren() is returning a single Collider2D, and what you want is an array of Collider2D's, or Collider2D[]. What you'll want to do is something like this:
List<Collider2D> childrenColliders = new List<Collider2D>();
GetComponentsInChildren<Collider2D>(childrenColliders);
The first line replaces line 1 of your code and the second replaces line 15. You can then iterate through the list instead.
Also as a side note: if you are working with an unknown number of items you will probably want to use a List since Lists can grow and shrink as needed using the .Add() method, while arrays must be initialized with a set capacity.
Hope this helps,
Bentley
Thanks Bentley, it helped me solve my problem, and from now on I'll take your side note in consideration before using Arrays or a List.
Appreciated.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Trying to access points[0].position of type Transform. 1 Answer
Array Issue 1 Answer
C# String Array Has Missing or Incorrect Keycode Strings 2 Answers