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

Finding a unique object and moving towards it

Discussion in 'Scripting' started by isaacch, Jan 23, 2012.

  1. isaacch

    isaacch

    Joined:
    Oct 19, 2011
    Posts:
    20
    Is there any way to find a particular object and move towards that object ?

    Currently, I'm using Vector3.Lerp to move towards, and I want it to move towards, lets say, an object named ObjectA.

    However, there are a few such objects in the scene, so is there a way to access each ObjectA ?

    I've checked out instanceID to find the unique id, however, from what I read, the instanceIDs will be different when you load a new level and then come back to it (correct me if I'm wrong).

    Hope someone can point me in the right direction.

    Thank you ! :)
     
  2. G-man

    G-man

    Joined:
    Sep 1, 2011
    Posts:
    96
    if you want an object to move towards certain objects in the AI script of that object create a var of type Transform to hold the ObjectA(target)'s position and in code have the object turn and move towards that object. Now if there are multiple objects that are potential targets either have the moving object raycast a ray and if that ray hit a target move towards that target or determine which target to move towards by calculating distances between the moving object and the target.
     
  3. isaacch

    isaacch

    Joined:
    Oct 19, 2011
    Posts:
    20
    Thanks for your reply ! :)

    Why didn't I think of that, it works exactly as expected, thanks for your help !
     
  4. isaacch

    isaacch

    Joined:
    Oct 19, 2011
    Posts:
    20
    I've managed to get the object moving towards ObjectA with Vector3.Lerp.

    The code goes like this:

    player.transform.position = Vector3.Lerp(player.transform.position, transform.position, Time.time);

    However, the player object seems to 'jump' immediately to ObjectA's position without showing it slowly movin towards that position. I've tried Time.deltaTime too but both doesn't seem to work.

    Can anyone shed some light on this ?

    Thanks :)