- Home /
how to select an object with raycasting
Hi, Im making an rts and I have 2 classes, one which controls the mouse pointer, and another that controls unit movement. I am trying to make it so an individual unit is selected when i click on him. I got the code for selecting multiple units in another tutorial. I am trying to use raycasting to select an individual unit. So far i have this below, along with other code that is not shown:
Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition); //trying to single select
RaycastHit hit;
Debug.DrawRay (ray.origin, ray.direction * Mathf.Infinity, Color.red);
if (Input.GetMouseButtonDown (0)) {
if(Physics.Raycast(ray,out hit, Mathf.Infinity)){
Debug.Log(hit.collider.name); //prints the name of the object it is touching
//selected = hit.collider;
}
}else if(Input.GetMouseButtonUp(1)){
}
so, I am trying to make it so when the ray detects an object that is "Unit" (the name of the object I have) it changes its selected status to true. So I basically just need it to get the object that is hit and set its selected to true. Any ideas? Thanks in advance, im a bit new.
Without seeing the interface to your selection system, any answer would be guess work. Depending on how you have things setup, you might do something like:
SomeScript ss = hit.collider.GetComponent<SomeScript>();
ss.SetSelection();
But you may have implemented your selection as static class variables with a static function. In that case you might do:
SelectionClass.SetSelection(hit.collider.gameObject);
Then it would be:
Unit unit = hit.collider.GetComponent<Unit>();
if (unit != null) {
unit.selected = true;
}
Answer by camtronius · Apr 17, 2014 at 03:20 PM
@robertu I have a class called "Unit" which is applied to my Unit in the game. The Unit class has a boolean called "selected". I need to make it so when the Object "Unit" is hit by the raycast it sets the "selected" boolean to true for that hit object. Does that make more sense? Thanks,
Your answer
Follow this Question
Related Questions
How to use raycast on generated objects. 0 Answers
Change raycasting 1 Answer
Raycast not visible 1 Answer
Raycast returns null for no apparent reason 0 Answers
Click&Drag Misterious Disappearing! 1 Answer