- Home /
Is Update() the best way to handle mouse motion?
I'm making a simple 2D game, where a ship in the middle of the screen points to the mouse location. This is working no problem, as I've put some code in the Update() function to track the mouse location and point the ship to look at it:
var mousePos = Input.mousePosition;
mousePos.z = -(transform.position.y - Camera.mainCamera.transform.position.y);
var worldPos = Camera.mainCamera.ScreenToWorldPoint(mousePos);
transform.LookAt(worldPos);
However, I'm finding a noticeable performance hit when I use this approach, i.e., there is a bit of lag every time I move the mouse. I was thinking that maybe there's an Input.OnMouseMotion event handler, but no such luck.
Just wondering if there's a better way?
I just built my project and ran it is a web-browser, and I certainly do not notice the same performance hit. Perhaps it's just a result of running it in the Unity environment itself?
In short - Yes, it's the best way, and it's not a "Unity thing", either - all games handle input through the "Update()" function one way or another.
Answer by runevision · Jul 30, 2010 at 11:33 AM
The performance hit is probably not related to the mouse at all; none of the lines would be faster or slower depending on if the mouse moves or not.
However, since the transform will only be changed if the mouse moves, maybe that could be something to look into. For example, if you have a collider on the object you've moving, but no rigidbody, then there's a performance penalty in moving the object since it's assumed to be static (CharacterControllers are the exception from this).
Also, if you don't see any performance hit when building a player, then it's probably not a problem in your code. :)
Answer by Whimsical · Jul 29, 2010 at 06:31 PM
Without knowing what exactly else is happening in your project it's hard to tell what actually causes the performance bump. But it's save to say that Update() is the best place to put your functionality, given that you want it to be evaluated once every single frame. And there's no function in your four lines of code that is unnecessarily performance hungry, so by judging on these four lines of code: There isn't supposed to be a lack whatsoever.
What else are you doing when you move your ship?
Your answer
