0
\$\begingroup\$

I've got 2 first person controller scripts, one that handles functionality for basic movement, the other handling looking around. I also have a "CursorLockManager" script, that handles the cursor locking, as well as locking movement and looking (for when opening menus and such). At the beginning of the cursor lock script, in the start function, I have two GameObject.FindWithTag lines. One looks for the playerLook script, and the other looks for the playerMove script. I have them both set up the same way, but one of them isn't working.

First few lines of the CursorLockManager script:

public KeyCode menuKey; public PlayerLook playerLook; public PlayerMove playerMove; public bool menuIsOpened; public GameObject tempMenu; private void Start() { playerLook = GameObject.FindWithTag("Camera").GetComponent<PlayerLook>(); playerMove = GameObject.FindWithTag("FP_Controller").GetComponent<PlayerMove>(); } 

and the error Unity is throwing:

UnityException: Tag: Camera is not defined

enter image description here

Line 17 of the CursorLockManager:

 playerLook = GameObject.FindWithTag("Camera").GetComponent<PlayerLook>(); 

Any help would be greatly appreciated. If you need any further clarification as to anything else, I'd be glad to provide it to you.

\$\endgroup\$

1 Answer 1

0
\$\begingroup\$

It looks like you don't want to search by tags at all. If you ultimately want to find instances of a specific component, then search for that component instead, like this:

playerLook = FindObjectOfType<PlayerLook>(); playerMove = FindObjectOfType<PlayerMove>(); 

This searches directly for the component you want to use, so it's less sensitive to scene setup errors (like forgetting to create a tag called "Camera" or misspelling Unity's default "MainCamera" tag)

Or you can skip searching for them at all, and instead use a Singleton or Service Locator pattern to retrieve references to these key script instances more efficiently.


In Unity 2021.3.18 and newer, there's a faster alternative to FindObjectOfType when you know there's only one instance of this type anyway:

playerLook = FindAnyObjectByType<PlayerLook>(); playerMove = FindAnyObjectByType<PlayerMove>(); 

This skips invoking a sort to ensure the "first" instance is returned, since there's only going to be one of them anyway, making it more efficient.

\$\endgroup\$

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.