# Alternatives to Camera.main.ScreenToWorldPoint in Unity

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.

Thank you.

• 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? – DMGregory Feb 7 at 20:53

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();
}
}

• 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. – Candid Moon _Max_ Feb 8 at 15:57