- Home /
Selecting objects using raycasting
I'm working on a 3D towers of hanoi, and trying to specify which ring object the user is currently trying to manipulate. I have the following code within a script on a character controller. The code is in the Update() function. The ringSmall, ringMedium, and ringLarge scripts are attached to each corresponding ring object.
This works, however, I can only select each ring once, and then never again. Any suggestions?
var fwd = transform.TransformDirection(Vector3.forward);
var hit : RaycastHit;
if (Physics.Raycast(transform.position, fwd, hit))
{
if(hit.distance <= 5)
{
if(hit.collider.gameObject.tag == "small")
{
if(Input.GetMouseButtonDown(0))
{
ringSmall.isSelected = true;
print("Small Ring Selected");
}
}
if(hit.collider.gameObject.tag == "medium")
{
if(Input.GetMouseButtonDown(0))
{
ringMedium.isSelected = true;
print("Medium Ring Selected");
}
}
if(hit.collider.gameObject.tag == "large")
{
if(Input.GetMouseButtonDown(0))
{
ringLarge.isSelected = true;
print("Large Ring Selected");
}
}
}
Do you have any code that deselects the rings on some event? Cause from just code they stay selected after clicked once.
Also did you consider using mouse events on the rings and then passing whatever you need to the controller?
Yes, on each ring, I have code to set the other selections to false if that ring is selected. Here is the code snippet for when ringSmall.isSelected is true
if(isSelected == true)
{
ringLarge.isSelected = false;
ring$$anonymous$$edium.isSelected = false;
}
Also, what do you mean by mouse events? I'm using Input.Get$$anonymous$$ouseButtonDown(0) currently, but just to do the selecting if the ring is clicked on
Just to cover everything: Did you try doing prints to check if the raycast is hitting the rings? Do you do anything to the rings when they are selected or is it just limited to the isSelected bool for now?
As for mouse events, depending on how your game works you could use the On$$anonymous$$ouseDown() and other $$anonymous$$ouse functions on the rings, but that only works if the player is supposed to point at them with the mouse. But if you need to point the camera or the player at them then ignore it.
I just tried adding print statements under the if(hit.collider.gameObject.tag == "small/medium/large") to check if the raycast is hitting the rings, again, it only does each ring once and then is just stuck on whatever the last one is