- Home /
GetTouch - to cache or not to cache?
Hi to all!
Optimizing my touch controller script, and wondering about the following example in the docs (comments removed, stripped down to essentials) :
function Update () {
for (var i = 0; i < Input.touchCount; ++i) {
if (Input.GetTouch(i).phase == TouchPhase.Began) {
var ray = Camera.main.ScreenPointToRay (Input.GetTouch(i).position);
}
}
}
Is there no overhead involved in repeatedly calling GetTouch(i), instead of caching the Touch object at the beginning of every iteration? I followed this model, and call GetTouch a bunch of times in my TouchController script. Just to make sure I'm clear, would this be better, performance wise:
myTouches = new Touch[maxTouches];
function Update () {
for (var i = 0; i < Input.touchCount; ++i) {
myTouches[i]=Input.GetTouch(i);
if (myTouches(i).phase == TouchPhase.Began) {
var ray = Camera.main.ScreenPointToRay (myTouches(i).position);
}
}
}
Thanks for your insights!
Answer by DaveA · Mar 28, 2012 at 09:36 PM
you can also use Input.touches instead of GetTouch
Which, allocates temp vars, not an improvement performance wise... And it doesn't answer my question. Thanks nevertheless!
I would have thought it was allocated by the Input class in any case, and copying GetTouch to another array would be duplicating that data that's already sitting around. Are you saying that accessing Input.touches[0] allocates temp vars at that time, not when a touch is detected?
Ok, after a bit of research I think I have a better understanding. Input.touches returning the Touch objects of the previous frame, it must allocate the variables wether called or not.
But GetTouch()'s syntax looks like a function, which makes me wonder if there is any overhead in calling it repeatedly ins$$anonymous$$d of caching...
Your answer
![](https://koobas.hobune.stream/wayback/20220613065643im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Are OnGUI calculations cached? 1 Answer
does interpolation full up some kind of cache over time 1 Answer
Pool/Cache Unity colors when used by many objects 0 Answers
What is a reasonable number of draw calls relative to one hardware configuration ? 6 Answers
Should I export my room with all the objects in it or rearrange in Unity? 1 Answer