I am using array of Box collider but its throwing error

Its giving this error ‘ArgumentException: GetComponent requires that the requested component ‘BoxCollider[ ]’ derives from MonoBehaviour or Component or is an interface.’

It basically stores weapons used in the game which are box colliders.

Here is the code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyAttack : MonoBehaviour
{
    [SerializeField] private float range = 3f;
    [SerializeField] private float timeBetweenAttacks = 1f;

    private Animator anim;
    private GameObject player;
    private bool playerInRange;
  [B]  private BoxCollider[] weaponColliders;[/B]

    // Start is called before the first frame update
    void Start()
    {
        weaponColliders = GetComponentInChildren <BoxCollider[]> ();
        player = GameManager.instance.Player;       
        anim = GetComponent <Animator> ();
        StartCoroutine (attack());
    }

    // Update is called once per frame
    void Update()
    {
        if(Vector3.Distance(transform.position,GameManager.instance.Player.transform.position) < range)
        {
            playerInRange = true;
        }else{
           playerInRange = false;
        }
       
    }

    public IEnumerator attack()
    {
        Debug.Log("Hello");
        if(playerInRange && !GameManager.instance.GameOver)
        {
            anim.Play("Attack");
            yield return new WaitForSeconds(timeBetweenAttacks);
        }
        yield return null;
        StartCoroutine(attack());       
    }

    public void EnemyBeginAttack(){
        foreach(var weapon in weaponColliders){
            weapon.enabled = true;
        }
    }

    public void EnemyEndAttack(){
        foreach(var weapon in weaponColliders){
            weapon.enabled = false;
        }
    }
}

There are plural flavors of ALL of the GetComponent calls. Those calls return arrays, which appears to be what you want. Go check the docs.

I tried checking docs, but found nothing relevant. Any particular section I can check?

Steps to success with documentation:

Strategy #1:

  • find the method you’re using (GetComponent())

  • click the link to go up to the class it came from (GameObject)

  • look for that same method GetComponent()

  • note that immediately next to it is the plural version I spoke of.

Strategy #2:

  • using Google, type Unity GetComponent and see what other suggestions appear… do any of those look plural?

When I type weaponColliders = GetComponentInChildren <BoxCollider[]> (); it gives error Cannot implicitly convert type ‘UnityEngine.BoxCollider’ to ‘UnityEngine.BoxCollider[ ]’ [Assembly-CSharp]. What could be the reason

Go look at the docs for what the difference is between:

  • GetComponentInChildren
  • GetComponentsInChildren

It matters. The first is singular, the second is plural.