gameobject does not contain a definition for getcomponent

Why can’t I access the transform of my player gameobject with this script?

public class Enemyfollow : MonoBehaviour
{
    //variables
    public float speed;
    private Transform target;

    void Start()
    {
      target = GameObject.FindGameObjectsWithTag("Player").GetComponent<Transform>();
    }
     void Update()
    {   if(Vector2.Distance(transform.position, target.position) > 3)
       transform.position = Vector2.MoveTowards(transform.position, target.position * speed * Time.deltaTime);
    }
}
2 Likes

I think the problem might be that the method you’re using returns an array rather than a single object so your variable designed to store a single object therefore can’t store it. If it’s a game with multiple players then you need a way of distinguishing which player you want the AI to follow.

FindGameObject___s___WithTag

19 Likes

There won’t be more than one player.

In that case the correct line of code would probably look something like

target = GameObject.FindGameObjectsWithTag("Player")[0].GetComponent<Transform>();

given that the method appears to return an array. I’ve never used this method before so I might be wrong. If there’s only one player in the game, though, then why use a tag seeker in the first place? I would think the normal Find method just looking for the name “Player” would be a lot simpler to use.

1 Like

Fixed it with this, Thanks all.

public class Enemyfollow : MonoBehaviour
{
    //variables
    public float speed;
    private Transform target;

    void Start()
    {
      target = GameObject.FindGameObjectWithTag("Player").GetComponent<Transform>();
    }
     void Update()
    {   if(Vector2.Distance(transform.position, target.position) > 3)
       transform.position = Vector2.MoveTowards(transform.position, target.position,speed * Time.deltaTime);
    }
}
1 Like

This is also an example of why you need to read error messages carefully, and when asking for help, you should try to post an exact error message instead of paraphrasing.

GameObject has a definition of GetComponent, so it would be very confusing if the error said that it didn’t.

But presumably what the error message actually said was that GameObject[ ] has no definition of GetComponent, which would immediately tell a careful reader that you were operating on an array instead of an individual object.

3 Likes

I JUST STARTED MY FIRST EVER TIME CODING YESTERDAY AND I’VE BEEN STARING AT IT NOT UNDERSTANDING WHY IT ISNT WORKING. ALL BECAUSE I ADDED AN S. YOU’RE A LIFE SAVOR.

1 Like

Same, i have tried EVRYTHING in my hand to solve this, I have reinstalled all multiple times and still isn’t fixed. This is hell.