Hi !
I am trying to make a “UI interaction system” using a raycast in my VR project and here is what I came up with :
I use a raycast from a start point (from the hand/controller on 5 meters maximum) and check if it collides with anything with the “UIElement” Tag. If so, it displays a line (so the user can see where he is aiming). It also checks if the gameobject that was hit by the raycast has a Button component and, if it has one and the player presses the trigger, it calls the button’s onClick() method.
All of this is used into a method that is called constantly in the FixedUpdate. But I have a huge problem. Since VR needs a good 75-90 FPS to run smoothly, I can’t afford the fps drop that occurs with my solution. So what happens is that everything runs correctly, until I aim at a UIElement and the line appears. And at that point, I go from a constant 90 FPS to 45-62 FPS.
What can I do to improve this ?
In the profiler, here is what I got :
void FixedUpdate()
{
RayForUI();
}
//-------------------------------------------------
private void RayForUI()
{
RaycastHit hit;
LineRenderer rayLine = rayCastStartPoint.parent.GetComponent<LineRenderer>();
Physics.Raycast(rayCastStartPoint.position, rayCastStartPoint.forward, out hit, raycastMaxDistance, RaycastCollidableLayers);
if (hit.collider != null)
{
if(hit.collider.CompareTag("UIElement"))
{
Button bt = hit.collider.GetComponent<Button>();
rayLine.colorGradient = GradColor(); //just a method to set a gradient to the line
rayLine.startWidth = lineWidthStart;
rayLine.endWidth = lineWidthEnd;
Debug.Log(hit.collider.name);
Debug.DrawRay(rayCastStartPoint.transform.position, rayCastStartPoint.forward * hit.distance, Color.blue);
Vector3 endPos = hit.point;
rayLine.SetPositions(new Vector3[] { rayCastStartPoint.position, endPos });
rayLine.enabled = true;
if (bt != null)
{
Button button = hit.collider.GetComponent<Button>();
ColorBlock colors = button.colors;
colors.normalColor = HoverONColor;
button.colors = colors;
if (SteamVR_Input._default.inActions.GrabPinch.GetStateUp(hand))
{
bt.onClick.Invoke();
}
}
else //here, It is supposed to reset the color of the button when I don't hover over it (but I think it a little overhead) what do you suggest ?
{
Button button = this.gameObject.GetComponent<Button>();
ColorBlock colors = button.colors;
colors.normalColor = HoverOFFColor;
button.colors = colors;
}