Visual studio не показывает ошибки unity

I’ve been using Visual Studio (2017) for quite a long time now, to program mostly in C#, for Unity games. Recently though, I noticed that it was not displaying any errors in the code anymore, or at least most of them. I initially started making some small tests, for example removing variables that were being used multiple times in the scripts. Visual Studio was not showing any errors, while when going back to Unity, it was showing all the correct errors in the console (as always). Instead, if I tried to remove a parenthese, it was, after a bit, showing errors all over the place. Again, it was really strange.

After one day, I was still testing, and I noticed that if I first opened Visual Studio, and then in «recent» I clicked on the the .sln file, that opened all the scripts for one Unity project, it was immediately showing all the right errors, like it had always done and how (I think) it should always do. I started looking for some differences between what I was seeing there, and what I was seeing when opening the .cs files (in the way that wasn’t working):

  • At the top, I wasn’t seeing «Debug» and «Any CPU» how I was when it was working:

enter image description here
enter image description here

  • Another thing was that, between the «Project» and the «Debug» buttons (at the top, that open the drop-down lists), I didn’t have the «Compile» button.

  • Also, under the the «Debug» drop-down many options like «start debug» were not available / disabled.

  • At the top left, under the left-most script name, I have «External files» instead of «Assembly-CSharp»

  • At the right of where there should be «Debug» and «Any CPU», I have «Connect» instead of «Start» (Or something similar, my system’s language is not english, these are translations)

Another (maybe less relevant) thing that has changed from before, when it was working:

  • I have installed Visual Studio 2019, and uninstalled after a few minutes (I’ve always preferred Visual Studio 2017!).

Programming without seeing the errors realtime takes much more time, so I’d really like to fix this problem, if it is possible to do so. Is there anything that I have to activate? Did I accidentally press a combination of keys?

Thanks in advance! :)

В этом коде visual studio даже не показало ошибку,почему так?
public class pig : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
Debug.Log(123);
Debug.даыаф;
}

// Update is called once per frame
void Update()
{

}
}


  • Вопрос задан

  • 205 просмотров

Пригласить эксперта

вероятнее всего у тебя старая версия visual studio, или же попробуй в unity нажать на «Edit» , далее на «prefences», после External tools
6404f9a76559d126123310.jpeg
после в External script editor измени на самую новую версию visual studio.

либо же можешь полазить в настройках визуал студио —
6404fa39c9f63292465945.jpeg


  • Показать ещё
    Загружается…

21 сент. 2023, в 20:54

10000 руб./за проект

21 сент. 2023, в 20:40

20000 руб./за проект

21 сент. 2023, в 19:28

10000 руб./за проект

Минуточку внимания

Я использую Visual Studio (2017) довольно давно, чтобы программировать в основном на C# для игр Unity. Однако недавно я заметил, что он больше не отображает никаких ошибок в коде, или, по крайней мере, большинство из них. Сначала я начал делать небольшие тесты, например, удаляя переменные, которые многократно использовались в скриптах. Visual Studio не показывала никаких ошибок, а при возврате в Unity отображала все правильные ошибки в консоли (как всегда). Вместо этого, если бы я попытался убрать круглую скобку, через некоторое время она показывала ошибки повсюду. Опять же, это было действительно странно.

Спустя один день я все еще проводил тестирование и заметил, что если я сначала открыл Visual Studio, а затем в «недавнем» щелкнул файл .sln, открывший все сценарии для одного проекта Unity, он сразу показал все правильные ошибки, как это было всегда и как (я думаю) всегда должно быть. Я начал искать некоторые различия между тем, что я там видел, и тем, что я видел при открытии файлов .cs (таким образом, который не работал):

  • Наверху я не видел «Отладка» и «Любой процессор», как это было, когда он работал:

  • Другое дело, что между кнопками«Проект» и «Отладка» (вверху, открывающими раскрывающиеся списки) у меня не было кнопки «Скомпилировать».

  • Кроме того, в раскрывающемсясписке «Отладка» многие параметры, такие как «начать отладку», были недоступны / отключены.

  • Вверху слева, подкрайним левым именем скрипта, у меня есть «Внешние файлы» вместо «Assembly-CSharp».

  • Справа от того места, где должны быть «Отладка» и «Любой процессор», у меня есть «Подключить» вместо «Пуск» (или что-то подобное, язык моей системы не английский, это переводы)

Еще одна (возможно, менее актуальная) вещь, которая изменилась по сравнению с предыдущим, когда работала:

  • Я установил Visual Studio 2019 и удалил его через несколько минут (я всегда предпочитал Visual Studio 2017!).

Программирование без просмотра ошибок в реальном времени занимает гораздо больше времени, поэтому я бы очень хотел исправить эту проблему, если это возможно. Мне нужно что-нибудь активировать? Я случайно нажал комбинацию клавиш?

Заранее спасибо!:)

2020-05-27 17:34

9
ответов

Решение

Удаление файла.suo может помочь при неустойчивом поведении Visual Studio.

Файл содержит пользовательские настройки решения, включая точки останова, параметры отладки, закладки, и может быть поврежден или сохранен в нежелательном состоянии.

Если вы удалите его, новый файл.suo будет создан после повторного открытия решения в Visual Studio.

2020-06-04 12:53

Просто откройте форму списка ошибок View -> Error List или используйте ярлык Ctrl + \, E

2020-05-27 18:50

У меня тоже была эта проблема. Для меня это было вызвано открытием проекта вместо решения. Когда я открыл решение (файл .sln), все функции редактора начали работать.



15 июл ’21 в 16:17
2021-07-15 16:17

2021-07-15 16:17

Вам нужно включить ошибки подчеркивания в параметрах редактора в Visual Studio.

Эти варианты можно найти здесь:

Инструменты> Параметры> Текстовый редактор> C# > Дополнительно> Справка редактора

2020-05-29 19:09

У меня была такая же проблема в предварительной версии VS 2022.

Решением было проверить: Инструменты -> Параметры -> Текстовый редактор -> Общие -> Показывать волнистые линии ошибок.

Диалог настроек



18 авг ’21 в 02:22
2021-08-18 02:22

2021-08-18 02:22

Перейдите к настройке, введите Error Squiggles в настройках поиска и включите его.

2021-11-17 21:18

Для меня это был файл, который не был включен в проект.

После переключения некоторых веток вновь созданный файл перестал включаться в проект и не считывался на наличие ошибок. Мне пришлось нажать «Показать все файлы» в обозревателе решений, щелкнуть правой кнопкой мыши файл и выбрать «Включить в проект».

2022-07-07 09:24

Попробуйте удалить папку bin в каталоге проекта, это заставит перекомпилировать код.

Просто не забудьте сохранить в папке bin все файлы .dll, которые могли быть добавлены вручную. Вы можете увидеть их в разделе «Ссылки» в обозревателе решений и добавить их обратно после.

Visual Studio повторно создаст папку bin, не волнуйтесь!

2021-04-16 16:51

У меня была эта проблема какое-то время, и это было связано с моим решением. Я зашел в свой проект, провел анализ кода, а затем перенаправил его на более старую версию.

Понятия не имею, почему это сработало, но проблема устранилась.

2020-05-30 07:20

Возможны несколько причин, почему Visual Studio не подсказывает Unity. Одна из них может быть неправильная настройка среды разработки. Возможно, необходимо установить или обновить плагины и расширения, связанные с Unity. Также, возможно, нужно проверить правильность конфигурации проекта Unity, чтобы Visual Studio мог обнаружить его и предоставить подсказки и автодополнение. В некоторых случаях, это может быть связано с обновлением самой Visual Studio или Unity, поэтому важно проверить их совместимость. Если обычные решения не помогли, то стоит обратиться к сообществу разработчиков Unity или официальным источникам для получения дополнительной информации и решения проблемы.

Как исправить ошибку связанную с Unity движком

Visual Studio не подсказывает в Unity #shorts #unity #unity3d

Ошибка #2 — Visual Studio не подсвечивает код из Unity

Научу создать игру на Unity за 5 минут!!! — Gamicle

Unity\\C#: Установка unity, visual code, visual studio. Исправление ошибок

—100% СПОСОБ ИСПРАВЛЕНИЕ ОШИБКИ Unity 2019.4…—😎

Как ВКЛЮЧИТЬ подсказки в Unity? — Microsoft Visual Studio, C#, Tutorial

If you like our article, do take some time to check out the rest of our site! We have plenty of Unity-related posts, tutorials and even some content on web development!

One of the biggest perks of using Microsoft’s Visual Studio to write your Unity scripts is IntelliSense — a code completion aid in Visual Studio that offers suggestions as you write your code, and contextually presents you with information about classes, properties and methods that you are working with.

Given Unity’s enormous scripting API, IntelliSense is a tremendously helpful feature, especially for coders who are beginning their foray into developing games and software with Unity; and while we’d love to say that IntelliSense is automatically set up and linked to Unity’s API when you install it with the Unity Editor, sometimes that’s just not the case. So, if you’ve got both Unity and Visual Studio set up, but find that IntelliSense is still not offering Unity API suggestions, then this guide is for you.

Visual Studio's IntelliSense for Unity
If IntelliSense doesn’t automatically offer Unity API suggestions like these, then it isn’t working.

There can be many reasons why IntelliSense is failing to work properly on your device, and we are assuming that you’ve already scoured the Internet a fair bit before stumbling on our article. Hence, we’ve put together a table of contents of sorts below, so if you’ve already tried some of the solutions we have, you can skip right through them.

If you prefer watching a video instead of reading, do check out our video guide for this post too.

  1. Is my IntelliSense not working?
  2. Getting IntelliSense working
    1. Open your scripts from Unity
    2. Setting Unity’s External Script Editor
    3. Visual Studio Tools for Unity
    4. Check your .NET API compatibility level
    5. Check if the Assembly-Csharp solution is loaded
    6. Regenerating your Unity project files
  3. Conclusion
  4. Video guide

Article continues after the advertisement:


1. Is my IntelliSense not working?

For IntelliSense to detect and work with Unity’s API, Visual Studio needs to:

  1. Be linked to the Unity Editor, and;
  2. Have the appropriate extensions installed (read further to find out what they are)

If you’ve installed Visual Studio via Unity Hub, this can have been automatically set up, but not always. Due to the bevy of ways which you can install Unity and Visual Studio, misconfigurations can happen, and you might end up with Visual Studio not integrating itself into Unity, and an IntelliSense feature that is not properly linked to Unity’s API.

We’ve found that, when installing some versions of Unity 2019 and 2020, Visual Studio does not always integrate with Unity’s API by default. So if things are not working properly, it might not be caused by misconfiguration on your end.

Is IntelliSense set up?
If you see these things, then IntelliSense hasn’t been set up on your device.

To check if IntelliSense is properly set up, open any script from the Unity Editor, and look out for 2 things:

  1. Whether the top-left dropdown says Miscellaneous Files. If it does, then IntelliSense is not set up (it has to say Assembly-Csharp.
  2. Try declaring a Unity variable, like a GameObject. If IntelliSense is properly set up, Visual Studio should have an auto-complete suggestion for you before you finish typing.

2. Getting IntelliSense working

So if IntelliSense isn’t working for you, what should you do?

a. Open your scripts from Unity

Before you try anything else from here, first make sure that your scripts are opened from within Unity, i.e. whenever you want to edit your scripts, double-click on them in the Unity Editor so that Visual Studio is opened by Unity.

If IntelliSense still doesn’t work when you do this, then continue onto the steps below:

b. Setting Unity’s External Script Editor

From the Unity Editor, access the Preferences window from Edit > Preferences. Then, click on 1) the External Tools tab.

Setting the External Script Editor
You’ll need to set the External Script Editor.

Set 2) the External Script Editor to the version of Visual Studio that you installed alongside Unity, then click on 3) the Regenerate project files button (if it’s there).

Once that’s done, restart Visual Studio and see if IntelliSense now works. If it still doesn’t, then you might be missing…

If Visual Studio doesn’t appear on the dropdown, you will have to use the Browse… option (pictured above) to find it. It’s typically under C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\Common7\IDE\devenv.exe for Windows devices.


Article continues after the advertisement:

Unity — The Dev Days of Summer


c. Visual Studio Tools for Unity

To install this, open Visual Studio and go to Tools > Get Tools and Features.

Accessing the Visual Studio Installer
This opens the Visual Studio Installer.

Note: You’ll need administrator permissions to open this window, as it makes changes to the Visual Studio installation on your computer.

Once the installer is open, go to Workloads and find Game development with Unity. Check the box, and then click on the Modify button on the bottom-right corner to begin installation.

Finding the Game development with Unity workload
Install the Game development with Unity workload.

A popup may ask you to close certain processes before beginning installation. If this happens, close your Visual Studio project and the Unity Editor application.

When installation completes, restart both Unity and Visual Studio, then check to see if IntelliSense now works.

The Games development with Unity workload actually installs 2 additional Visual Studio components — Visual Studio Tools for Unity and C# and Visual Basic. You can install both modules individually by going to the Individual components tab, and checking both components in the list that is shown.

Finding Visual Studio Tools for Unity

Article continues after the advertisement:


d. Check your .NET API compatibility level

If IntelliSense still refuses to work, you can open the Unity Editor and head to Edit > Project Settings and access the Player (or Player Settings) tab. Scroll down to the Other Settings sub-tab, and find the Api Compatibility Level dropdown under the Configuration heading.

You want to set the Api Compatibility Level to a different option, and see which is the one that works for your device.

Setting the Api Compatibility Level
The Api Compatibility Level setting is nested quite deep in.

e. Check if the Assembly-Csharp solution is loaded

If you have tried all of the above steps, but your Intellisense still doesn’t work, then it may be because you have accidentally unloaded the solution (i.e. what Visual Studio calls their project setting files) for your project. To check if that is the case:

  1. In Visual Studio, go to View > Solution Explorer.
  2. The Solution window should pop up by the side of Visual Studio. Check if there is a tab that says Assembly-Csharp (unloaded). If there isn’t, you likely have not set your external script editor, or downloaded Visual Studio Tools for Unity.
  3. Right-click on Assembly-Csharp (unloaded) and select Reload project. The dropdown on the top left corner of Visual Studio should change from Miscellaneous Files to Assembly-Csharp. If that happens, congratulations! IntelliSense should now be working.
  4. If (3) fails, close Visual Studio and reopen it again.

Below is a GIF demonstrating the steps above.

Reloading your Unity project solution
You may have accidentally unloaded the project solution, which caused IntelliSense to not work.

f. Manually regenerating your Unity project files

If the above solutions we’ve proposed did not work for you, you can also try this solution from one of our comment contributions.

Note: Back up your Unity project before trying this, as we are deleting some essential project files and letting Unity regenerate them.

  1. Close both Visual Studio and Unity on your device.
  2. Remove all .sln and .csproj files in your Unity project folder.
  3. Remove the .vs and Library folders in your Unity project folder.
  4. Re-open the project in Unity, then go to Assets > Open C# Project to open Visual Studio.

3. Conclusion

As with the other articles on the blog, we’d love if you leave a comment below, especially if you:

  1. Find any errors in this article, or;
  2. Find an IntelliSense fix that is not listed in this article

Your comments will add on to the information that is already here, and help other future readers!

4. Video guide

Is this post not visual enough? Perhaps our video guide of this post can help.


Article continues after the advertisement:


Понравилась статья? Поделить с друзьями:
  • Visual studio кодировка ошибок
  • Vita nostra работа над ошибками аудиокнига скачать торрент
  • Visual studio код ошибки 0x80070003
  • Visual studio список ошибок пропал
  • Visual studio как посмотреть ошибки