Error Cs1061

Hello,

I cant seem to figure out how i would handle this better/correctly
I’m getting the error posted in the title “GameObject[ ]’ does not contain a definition for ‘GetComponent’ and no accessible extension method ‘GetComponent’ accepting a first argument of type ‘GameObject[ ]’ could be found (are you missing a using directive or an assembly reference?)”

any help is appreciated thank you in advance.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class foodDestroyer : MonoBehaviour
{


    public GameObject[] Cell;


    // Start is called before the first frame update
    void Start()
    {
        Cell = GameObject.FindGameObjectsWithTag("Cell");
    }

    // Update is called once per frame
    void Update()
    {
       
    }


    void OnTriggerEnter(Collider other)
    {
        if(other.gameObject.CompareTag("Cell"))
        {
            Cell.GetComponent<cellController>().foodEaten++;
            Destroy(gameObject);
        }
    }


}

It is a good practice to name classes starting with uppercase. Now Your code is hard to read.
Still, what I think, can solve your problem is to call the GetComponent method on other.gameobject instead od the Cell.

You’re using FindObjectsWithTag, i.e. the plural version which returns an array of GameObjects. You cannot invoke a type’s specific method on an array of that type.

I assume you only have one controller in that scene, so it’s probably FindObjectWithTag that you’re looking for. If you’re having multiple controllers for some reason, you’ll need to iterate the array and apply your logic to each of the contained objects.

1 Like

Thank you Kretoskar, but can you elaborate on how my code is hard to read is it just because the name or what? I’m fairly new at this and am trying to learn.

Personally I wouldn’t say it’s difficult to read, I mean, it’s properly indented and there’s no cryptic mess of instructions. Though he’s right about conventions, especially about the type names. Almost everywhere in C# (even in many other languages) you’ll find type names that follow the convention of using PascalCase.

So the class name should be FoodDestroyer? Thats all thats wrong?

It’s not “wrong” and it wouldn’t solve the issue you encountered. In order to resolve the error, take a look at my first post in this thread.

praise you for this answer. sorted me out nicely.