0
\$\begingroup\$

What are alternatives to Camera.main.ScreenToWorldPoint in Unity?

So, here is my code (just the piece which is relevant for the question):

void sendPointerMove(ref Vector3 mousePosition)
{
    lastMousePosition = mousePosition;

    Vector3 mousePositionInWorld = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    PointerData pointerData = new PointerData(
       mousePositionInWorld: mousePositionInWorld
    );
}

void FixedUpdate()
{
    Vector3 mousePosition = Input.mousePosition;

    if (needToSendPointerMove(mousePosition))
    {
       sendPointerMove(ref mousePosition);
    }
}

I am using JetBrains Rider to develop for Unity. And the ide suggests me the following about my sendPointerMove function invocation inside the FixedUpdate:

Expensive method invocation

I am sure that the issue is due to the Camera.main.ScreenToWorldPoint because when I comment out the part the warning disappears.

enter image description here

enter image description here

Thank you.

\$\endgroup\$
  • \$\begingroup\$ Let's analyze this a bit deeper, and separate the process of searching for the camera (Camera.main) from the process of mapping the input vector (ScreenToWorldPoint(mousePosition)). Do you find the problem is improved if you cache a reference to the camera once, rather than searching for it every FixedUpdate? \$\endgroup\$ – DMGregory Feb 7 at 20:53
3
\$\begingroup\$

Basically, when you call Camera.main, Unity internally uses the FindGameObjectsWithTag to search through all of the objects in your scene that have the 'MainCamera' tag, returning the first active one. Since this will always be slower than a direct reference to it, you should cache it. You can declare it as a member variable and then initialize it inside your Start function.

This sort of pseudo code gives an example

using UnityEngine;

public class MyScript : MonoBehaviour
{  
    Camera cam;

    void Start()
    {
        cam = Camera.main;
    }

    void ConvertMousePos()
    {
        Vector3 mousePositionInWorld = cam.ScreenToWorldPoint(Input.mousePosition);
    }

    void FixedUpdate()
    {
        ConvertMousePos();
    }
}
\$\endgroup\$
  • 1
    \$\begingroup\$ It's definitely slower to use Camera.main because it goes through every game object on the scene comparing tags until it finds one that fits. \$\endgroup\$ – Candid Moon _Max_ Feb 8 at 15:57

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.