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

Translate Over Time Code Issue

Discussion in 'Scripting' started by coxy17, May 4, 2015.

  1. coxy17

    coxy17

    Joined:
    Sep 27, 2013
    Posts:
    126
    Hi, im currently using the following code to make a moving platform. Its works fine, however, if i duplicate the object and code. My game runs really slowly, is it due to the code structure? as i want to make it into a prefab and have multiple moving platforms, Any help as to why would be great!

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class MovingPlatform : MonoBehaviour {
    5.  
    6.     public Transform DestinationSpot;
    7.     public Transform OriginSpot;
    8.     public float Speed;
    9.     public bool Switch = false;
    10.     private float pauseTime;
    11.     public float delayBeforeMoving;
    12.     private bool arrivedAtOurDestination = false;
    13.  
    14. void FixedUpdate()
    15. {
    16.     // For these 2 if statements, it's checking the position of the platform.
    17.     // If it's at the destination spot, it sets Switch to true.
    18.     if((transform.position == DestinationSpot.position) && !arrivedAtOurDestination)
    19.     {
    20.     Switch = true;
    21.     pauseTime = Time.time + delayBeforeMoving;
    22.     arrivedAtOurDestination = true;
    23.     }
    24.     if((transform.position == OriginSpot.position) && !arrivedAtOurDestination)
    25.     {
    26.     Switch = false;
    27.     pauseTime = Time.time + delayBeforeMoving;
    28.     arrivedAtOurDestination = true;
    29.     }
    30.  
    31.     // If Switch becomes true, it tells the platform to move to its Origin.
    32.     if(Switch && (Time.time > pauseTime))
    33.     {
    34.     transform.position = Vector3.MoveTowards(transform.position, OriginSpot.position, Speed);
    35.     arrivedAtOurDestination = false;
    36.     }
    37.     else if (Time.time > pauseTime)
    38.     {
    39.     // If Switch is false, it tells the platform to move to the destination.
    40.     transform.position = Vector3.MoveTowards(transform.position, DestinationSpot.position, Speed);
    41.     arrivedAtOurDestination = false;
    42.     }
    43.     }
    44. }