I'm used to Java/Processing, some help with new() please

Hi all, I’m more familiar with Java/Processing, where I do my utmost to avoid creating objects in the main draw loop so the code below feels kinda wrong. Would someone be kind enough to look over my code and tell me if there’s a better way of doing what I’m doing below.

I want this object to ease towards the target object on Y but for it to stay fixed at the same x position.

Your feedback would be greatly appreciated, and thanks for your time.

Dave.

public class follow : MonoBehaviour {

public GameObject target;
public float easing;
private Vector3 offset, middle, final;

void Start () 
{
	offset = target.transform.position - transform.position; 
}


void Update () 
{
	middle = target.transform.position - offset;
	final = Vector3.Lerp(transform.position, middle, easing);
	transform.position = new Vector3(middle.x, final.y, final.z);
}

}

Two really obvious options:

  1. Use iTween for your animation and specify a Y parameter only in your MoveTowards
  2. Build your target vector to nullify the x position before you apply easing via Lerp.

I agree with your general notion, that one should generally beware of creating new objects in draw loops. But there are a few things you're missing here. :)

Vector3 is not an object. It's a struct. As such, you're creating a new value type each frame, not a reference type. This means creating a new Vector3 behaves the same in terms of memory allocation as writing "classInteger = 5", assuming classInteger is a variable of type integer defined by the class. Surely, no one is going to object to doing that in update.

Note, also, that types declared in the scope of some method (as opposed to the fields of a class) are allocated on the stack, not on the heap. So the memory reserved for such allocation gets popped off the stack again when the method (Update, here) leaves scope, and therefore has no impact on garbage collection.