I have some very simple code in my project that allows me to drag objects around the screen (2D) with the mouse:
Vector3 point;
void OnMouseDrag()
{
point = Camera.main.ScreenToWorldPoint (Input.mousePosition);
point.z = myTransform.position.z;
myTransform.position = point;
}
Note that ‘myTransform’ is this gameobject’s cached transform. I added this a while ago and it works perfectly fine. I’m finishing up my project now and going back through to optimize code, and took another look at this and realized that it’s doing something I hadn’t initially realized. Because OnMouseDrag() is being called every frame, the code is actually bouncing the z position of my ‘point’ variable back and forth between the mouse’s z position and this object’s z position every single frame, which is unnecessary. I know that’s not necessarily performance intensive, but it bugs me knowing that it’s happening in my code and might be eating up tiny amounts of precious cycles.
I can see some obvious ways to fix it, but I’m honestly not sure if they’re any more efficient. For example, I could use 2 Vector3’s instead:
Vector3 point;
Vector3 pointTwo;
void OnMouseDrag()
{
point = Camera.main.ScreenToWorldPoint (Input.mousePosition);
pointTwo = new Vector3 (point.x, point.y, myTransform.position.z);
myTransform.position = pointTwo;
}
So now I’m not bouncing the z position of either variable back and forth, but I’m creating a new Vector3 every single frame which seems even worse.
Am I overthinking this? Would you consider my original code inefficient because of that z coordinate?