Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Setting GameObject position doesn't work with NavMesh

Discussion in 'Physics' started by DanVioletSagmiller, Sep 14, 2015.

  1. DanVioletSagmiller

    DanVioletSagmiller

    Joined:
    Aug 26, 2010
    Posts:
    203
    My code creates a unit. I need to detect if the collider is inside another collider. (I.e. if it is, I'll try random nearby locations next) I cannot use OnTriggerEnter/Exit, as that would take a frame for every test position.

    Details:

    I have an RTS, and the AI is generating units. The building has a box collider and a NavMeshObstacle component. The Unit has a Sphere Collider and a NavMeshAgent.

    It always creates the Unit at the center of the base. I validated upon initial creation, that the point is the center or the target building.

    At one point on the map, this works perfectly. It pushes the drone unit out of the building, and it appears in front. As shown in this clip: http://screencast.com/t/fQPBd6Ku


    The problem. For some reason, with the building at another point on the map, the drone unit shows up halfway across the map. as shown in this clip: http://screencast.com/t/F5S3TvP8


    - Thanks for any help.
     
    Last edited: Sep 14, 2015
  2. DanVioletSagmiller

    DanVioletSagmiller

    Joined:
    Aug 26, 2010
    Posts:
    203
    I found the issue!

    Here is the code I originally had:
    - var go = GameObject.Instantiate(DronePrefab);
    - go.transform.position = target;

    The problem was that when an object is instantiated with the NavMeshAgent, it does some sort of a lock on its position. Then, when I set the position, it determines there was a mountain in the way, and acts like the vechicle was pushed into the mountain, pulling it back to that edge. The only reason the first location worked, was because the building was close to where the prefab was created.

    The solution:
    var go = (GameObject)GameObject.Instantiate(DronePrefab, target, DronePrefab.transform.position);
     
    Randallhbarber likes this.
  3. Baste

    Baste

    Joined:
    Jan 24, 2013
    Posts:
    6,201
    You could also use the NavMeshAgent's Warp method.

    NavMeshAgents does not want to have their transform's position manipulated directly. That usually leads to a bunch of issues.