- Home /
Avoid repeating code?
Hi guys, I have this code:
function checkForButtons()
{
var ray = Camera.main.ScreenPointToRay (Input.mousePosition);
var hit : RaycastHit;
if (Physics.Raycast (ray, hit, 200))
{
var objecthit:Transform = hit.transform as Transform;
if (hit.collider.name == "button_start")
{
print ("object clicked!");
}
}
}
Plain and simple way to detect a touch on an object, the problem here is that I have multiple objects with different names (or tags) that need to detect the touches, how can I use this code without re writtting it for every single object?
nested ifs, or a switch //////////// if{}else if{} else if{}
/////////// name = hit.collider.name
switch(name){ case "button_start" break; case "button_lol" break; }
Answer by whydoidoit · Oct 10, 2012 at 04:19 PM
Write a generic version of this script:
CheckForButton.js
function Update()
{
var ray = Camera.main.ScreenPointToRay (Input.mousePosition);
var hit : RaycastHit;
if (Physics.Raycast (ray, hit, 200))
{
hit.transform.SendMessage("Touched", hit, SendMessage.DontRequireReceiver);
}
}
Then put your code on the actual object being touched in a function Touched(hit : RaycastHit) - if you need to pass more parameters you would make up a class and put the hit as one of its members and then send an instance of that class to Touched.
This is what I'm talking about, thanks buddy!! great script!
Your answer
Follow this Question
Related Questions
Finding all Game Objects with multiple Tags 4 Answers
Can't get more than one object. 1 Answer
"Dynamic" static variables 1 Answer
Mouse click not working 1 Answer
object.ToString never equals the string 2 Answers