Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Can't Convert GameObject to Vector3

Discussion in 'Scripting' started by DelightfulGooglyeyes, Jan 13, 2022.

  1. DelightfulGooglyeyes

    DelightfulGooglyeyes

    Joined:
    Aug 24, 2021
    Posts:
    27
    Hello! I'm trying to make another turtle shell that automatically finds a game object and destroys it, instead of having to aim (I'm attempting to use the NavMeshAgent). I have a line of code that keeps giving me an error that im unable to fix. Here is the code:
    Code (CSharp):
    1.         agent.destination = GameObject.FindGameObjectWithTag("obstacle");
    And I'm receiving this error: Can't implicitly convert type 'UnityEngine.GameObject' to 'UnityEngine.Vector3'
     
  2. Deleted User

    Deleted User

    Guest

    Code (csharp):
    1. agent.destination = GameObject.FindGameObjectWithTag("obstacle").transform.position;
    You could just call destroy on the object.

    Code (csharp):
    1. Destroy(GameObject.FindGameObjectWithTag("obstacle"))
     
    DelightfulGooglyeyes and Bunny83 like this.
  3. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,893
    Because a GameObject is not a Vector3. The agent wants a specific position (expressed as a Vector3) to navigate to. You're trying to give it a reference to a GameObject and it has no idea what to do with that.

    You can give it the position the GameObject is at. That would make more sense:

    Code (CSharp):
    1. GameObject obstacle = GameObject.FindGameObjectWithTag("obstacle");
    2. Vector3 obstaclePosition = obstacle.transform.position;
    3. agent.destination = obstaclePosition;
     
    Last edited: Jan 13, 2022
    DelightfulGooglyeyes and Bunny83 like this.
  4. DelightfulGooglyeyes

    DelightfulGooglyeyes

    Joined:
    Aug 24, 2021
    Posts:
    27
    Thank you so much! The first example worked!