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

GameObject going berzerk

Discussion in 'Scripting' started by ma.parizeau, Nov 23, 2014.

  1. ma.parizeau

    ma.parizeau

    Joined:
    Mar 21, 2010
    Posts:
    116
    Hi all...

    Ok here's my problem:

    If I build my NPC from scratch (I know cause I've done it 4 time already!), place all of the components, save the prefab, play the scene again and again, Everything works fine, the NPC will walk on the floor from it's starting position, detect all collision properly and facing the proper direction.

    BUT, when I reload my project or after a long while and play the scene, the NPC will go berzerk. He will go through the collisions, won't start at his intended position, will go very, very, very fast. Basically it has a mind of its own.

    My NPC uses the same controller script as my player and I have no problem with my player. So for the collision detection, it will be the same behavior. for the velocity, it will be the same, etc.even if I comment out the RayCast and below, I still get this same problem.

    Code (CSharp):
    1.  
    2. private void Update()
    3. {
    4.              Animator.SetBool("isWalking", true);
    5.  
    6.             _controller.SetHorizontalForce(_direction.x * WalkSpeed); //_direction.x is set to -1.0f or 1.0f
    7.  
    8.             //check to see if we need to flip
    9.             Flip();
    10.  
    11.             //if we are close to player, run away...
    12.             var raycast = Physics2D.Raycast(transform.position, _direction, RayDistanceWalk, 1 << LayerMask.NameToLayer("Player"));
    13.             if (!raycast)
    14.                 return;
    15.  
    16.             //change direction and accelarate
    17.             WalkSpeed = SpeedMultiplier;
    18.             Flip();
    19. }
    20.  
    So any idea what might be the problem?
     
  2. djfunkey

    djfunkey

    Joined:
    Jul 16, 2012
    Posts:
    201
    Maybe set certain variables in your awake function or start function. It's hard to tell without the limited script.