Search Unity

This script keeps crashing my unity why?

Discussion in 'Scripting' started by zarvin, Apr 22, 2018.

  1. zarvin

    zarvin

    Joined:
    Mar 28, 2017
    Posts:
    14
    This script is supposed to move an object between two different cubes but it keeps crashing my unity no idea why i added a counter to get rid of the infinite loop but still crashes any idea i'm still pretty new to coding btw if you have a better suggestion for the movement between two cubes i would love to hear it thanks!


    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class MoveAsteroid : MonoBehaviour {
    6.     public Transform Target;
    7.     public Transform Target2;
    8.     public int speed;
    9.     public int reset = 1;
    10.     public int count = 0;
    11.  
    12.  
    13.     // Use this for initialization
    14.     void Start()
    15.     {
    16.     }
    17.  
    18.     // Update is called once per frame
    19.     void Update()
    20.     {
    21.         float step = speed * Time.deltaTime;
    22.         while (reset == 1)
    23.         {
    24.             transform.position = Vector3.MoveTowards(transform.position, Target.position, step);
    25.             if (transform.position == Target.position) {
    26.                 reset = 2;
    27.                 count++;
    28.             }
    29.         }
    30.         while (reset == 2) {
    31.             transform.position = Vector3.MoveTowards(transform.position, Target2.position, step);
    32.             if(transform.position == Target2.position) {
    33.                 reset = 1;
    34.                 count++;
    35.             }
    36.         }
    37.         if(count == 5)
    38.         {
    39.             reset = 0;
    40.         }
    41.     }
    42.  
    43. }
     
  2. tranos

    tranos

    Joined:
    Feb 19, 2014
    Posts:
    180
    You don't need a while in update. Just use an if or use while with a coroutine
     
  3. tonemcbride

    tonemcbride

    Joined:
    Sep 7, 2010
    Posts:
    1,089
    The main problem you have (apart from the while loop) is that you're comparing the 2 positions to see if it's reached the destination. In floating point maths that's not a good thing to do as they were very rarely match exactly (they may be 0.000001 out so your loop will never finish).

    A better idea is to check if they are 'close enough'. Instead of doing this:

    Code (CSharp):
    1. if (transform.position == Target.position) {
    you could do this:

    Code (CSharp):
    1. if ((transform.position - Target.position).magnitude < 0.01f ) {
    This would assume the cubes are close enough when the distance between them is less than 1cm.