Can't use accessor without GetComponent<>

So I have an accessor on this script, caching an array of players. It will be accessed by the multitudes of AI for pathfinding so that they don’t have to all go store copies of the list of players on each AI gameObject.

public class Control : MonoBehaviour {

    private GameObject[] Players;

    void Awake()
        Players = (GameObject[])GameObject.FindGameObjectsWithTag("Player");

    public GameObject[] GetPlayers()
        return Players;

On AI, for some reason I am unable to cache the Control.cs script directly to be able to call the accessor as it returns this error, which indicates that it isn’t able to get the accessor references for the script Control.cs which would be the GetPlayers() function.

error CS1061: Type
UnityEngine.Component' does not contain a definition for GetPlayers’
and no extension method GetPlayers' of type UnityEngine.Component’ could
be found (are you missing a using
directive or an assembly reference?)

on the following Code

Component controlScript = GameObject.Find("ControlObj").GetComponent<Control>();
GameObject[] playerArray = controlScript.GetPlayers();

where either of these work without a hitch

GameObject controlGO = GameObject.Find("ControlObj");
GameObject[] playerArray = controlGO.GetComponent<Control>().GetPlayers();
// It even lists the GetPlayers() command in the suggestions pop-up list.

//or simply

GameObject[] playerArray = GameObject.Find("ControlObj").GetComponent<Control>().GetPlayers();

My question is, why can’t I do it the way I said first by caching the script on the object (It’s not a nullreference to the script, I checked) and calling the accessor straight from there. Instead of having to use the GetComponent<> line before being able to call the accessor.

Maybe I’m missing something, but you’re creating an object of type Component, and expecting to be able to access a member of Control. I’m thinking this is maybe intellisense biting you in the ass? :slight_smile:

You’re getting the error because Component does not contain a method called “GetPlayer”. If you create the object as type Control, it should theoretically work (assuming you have a public method by that name of course).