Search Unity

Question NPC Spawns on wrong position and it's behavior changed.

Discussion in 'Editor & General Support' started by sadtomGames, Jan 5, 2021.

  1. sadtomGames

    sadtomGames

    Joined:
    Sep 12, 2018
    Posts:
    3
    Hello guys,

    in the project i've been working on, i made a robot companion, that follows the player. It's super simple code:
    Code (CSharp):
    1.  void Update()
    2.     {
    3.         this.transform.LookAt(Player.transform);
    4.         if(Vector3.Distance(this.transform.position, Player.transform.position)>2)
    5.         {
    6.             this.transform.Translate(Vector3.forward * Time.deltaTime);
    7.         }
    8.     }
    It works perfectly in the first scene, but when i create another scene, the bot spawns at some weird position and follows something else, but not the player. And yes, in the new scene, the "Player" variable is set on the new player in the new scene.

    Thanks.
     
  2. PraetorBlue

    PraetorBlue

    Joined:
    Dec 13, 2012
    Posts:
    7,909
    Your code doesn't make your object follow the player. It makes the object look at the player and then move along the positive Z axis. Maybe you meant transform.forward rather than Vector3.forward?

    Also you should probably use Vector3.MoveTowards so you don't overshoot the target.
     
  3. sadtomGames

    sadtomGames

    Joined:
    Sep 12, 2018
    Posts:
    3
    Unfortunately, transform.forward makes it move along the Z-axis, Vector3.forward makes it follow the player. Also, with that condition, it never overshoots the target. But the strange thing is, that in one scene, it perfectly works. But when i load the other scene, it breaks.
     
  4. sadtomGames

    sadtomGames

    Joined:
    Sep 12, 2018
    Posts:
    3
    Okay, it just randomly started working, i didn't change anything :D