Inefficient transform code.

I’ve developed this code to constantly place the object between the guardedObject and player at a specific distance. It’s functional, however doing so makes the game very, very slow. Is there a more efficient way to implement this?

void Update () {
		
		Vector3 NewPosition = -(guardedObject.transform.position - player.transform.position);
		transform.localPosition = NewPosition.normalized * guardDistance;

		
	}

EDIT: To clarify, guardDistance is a pre-determined float, currently set at 4. I made it a variable so I could adjust the distance if needed. Basically I want this object to always be 4 units away from Guarded Object, directly between it and the Player.

Unless you’ve got hundreds instances of that script, this won’t change much, but you could calculate the sqrt of guardDistance once at start and then use

transform.localPosition = (NewPosition / NewPosition.sqrMagnitude) * sqrt_of_guardDistance;

That way, you can save a sqrt per frame. You could calculate the direction, the magnitude and the * yourself and ignore one component (y), if the game is 2D, so you can save some calculation too. That’s hardly gonna change anything but it’s the best I can think of. Your problem is probably elsewhere.

.normalized uses a square root, which might be what’s slowing your game down. I don’t know how you compute guardDistance (probably also using .magnitude or Vector3.Distance(), which both use square roots, too), but you could use this approach instead:

trnasform.position=Mathf.Lerp(player.transform.position, guardedObject.transform.position, factor);

If factor is 0, object will be placed at player position, if it is 1, it will be placed at guardedObject position, and for values between that it will be…well, between them.