C# Code efficiency.

I have an array of cubes, all spawned at different heights.

Currently I have it so when the up button is pressed it transform them all to z = 0, keeping them in their current location on the x, y axis.

Here is my current code:

using UnityEngine;
using System.Collections;

     public class zeroObjects : MonoBehaviour {
     public bool move;
     public float duration = 0.5f;
     private float t;


 
     void Update() 
     {

     	 if(Input.GetKeyDown(KeyCode.UpArrow))
    {
        move = true ;
    }
          if (move)
          {
           double TLoc;

        TLoc = transform.position.y;


        t += Time.deltaTime / duration; 

        Vector3 posA = new Vector3(transform.position.x, transform.position.y, transform.position.z);
        Vector3 posB = new Vector3(transform.position.x, 0, transform.position.z);
        
        if(TLoc > 0){
            print(posA);
            transform.position = Vector3.Lerp(posA, posB, t);
        }

        if(TLoc == 0){
        	move = false;
        }
    }

     }
 }

It works.

But I am relatively new to unity, and have just started learning C#.

Is there a better way to achieve what I am doing? Or am I on the right track?

There’s nothing wrong specifically, if it does what you need. The only optimization I would make is to change the double to a float as the double is not necessary.

Another slight optimization would be to move the check for GetKeyDown() into a single management type class and then use a static variable in the cube class.

So you may create a management class like this:

public class Manager: MonoBehaviour {
     bool inFreeFall = false;

     void Update() 
     {
         if(Input.GetKeyDown(KeyCode.UpArrow) && (!inFreeFall))
         {
             inFreeFall = true;
             zeroObjects.StartFreefall();
         }
     }
}

Then in your zeroObjects class:

static bool movingDown = false;

static public void StartFreeFall() {
    movingDown = true;
}

void Update() {
    if (movingDown) {
        // Your code to move
    }
}

Create an empty game object in your scene and drop the Manager script on it. So now you are only testing for GetKeyDown() in one place. It probably is such a small optimization it’s not worth it. :slight_smile: