- Home /
Touch screen input - Optimisation
I'm rather new to scripting for mobile and the best solution I have found for detecting if an object is being touched is this:
if(Input.touchCount > 0) {
var hit : RaycastHit;
var ray = Camera.main.ScreenPointToRay (Input.mousePosition);
if (Physics.Raycast(ray, hit, distance)){
if (hit.collider.gameObject == something)
}
}
However, I have 50 objects that can be touched. This means that 50 rays are being cast.
How do I go about optimising this?
Answer by syclamoth · Mar 13, 2012 at 10:38 AM
Why do you need to do the raycast 50 times? Even if there's no way of detecting the correct object other than using an if-statement, why can't you just put it all under the first raycast?
if(Physics.Raycast(ray, hit, distance))
{
switch(hit.collider.gameObject)
{
case something:
{
// Do things
break;
}
case somethingElse:
{
// Do other things
break;
}
}
}
(and so on)
Or, if you have an array of touchable objects, you can do something like this-
if(touchableObjectCollection.Contains(hit.collider.gameObject))
{
// do stuff
}
(syntax is obviously dependent upon your exact implementation).
So you're suggesting I don't put the touch script on the object itself. That may well answer my question.
What I originally had was that script running on each object that I wanted to be touchable.
So ins$$anonymous$$d have a script to fire the ray and check if it has hit something "touchable"?
Yes, that's what I'm suggesting. If you have one master script that handles all touches, it can save you a lot of time.
Your answer
Follow this Question
Related Questions
Touch Input only working on Unity Remote 0 Answers
How to stop second finger from manipulating position of gui joystick 1 Answer
Detect the mouse swept direction and adding force to object. 0 Answers
Unity ads problem for mobile 0 Answers
Is there a built in method that works like OnMouseDown() but for touch input? 1 Answer