C# 언어에서 IComparable 인터페이스는 오브젝트 간의 일반적인 정렬 순서를 제공하는 메서드를 정의합니다. 이 인터페이스를 사용하면 객체를 정렬할 수 있는 능력을 추가로 제공할 수 있습니다. 이는 배열 또는 리스트의 정렬 메서드와 같이, 순서가 필요한 상황에서 유용합니다.
IComparable 인터페이스는 단일 메서드 CompareTo를 정의하며, 이 메서드는 현재 인스턴스와 비교 대상이 되는 오브젝트를 매개변수로 받아들입니다.
public interface IComparable {
int CompareTo(object obj);
}
CompareTo 메서드는 다음과 같이 동작합니다:
만약 현재 인스턴스가 매개변수로 제공된 오브젝트보다 "작을" 경우, 이 메서드는 음의 정수를 반환합니다. 만약 현재 인스턴스가 매개변수로 제공된 오브젝트와 "같을" 경우, 이 메서드는 0을 반환합니다. 만약 현재 인스턴스가 매개변수로 제공된 오브젝트보다 "클" 경우, 이 메서드는 양의 정수를 반환합니다. 따라서, IComparable을 구현하는 클래스를 작성할 때는 CompareTo 메서드를 통해 두 객체를 어떻게 비교할지 정의해야 합니다.
아래 예시는 Person 클래스가 IComparable 인터페이스를 구현하는 방법을 보여줍니다:
public class Person : IComparable {
public string Name { get; set; }
public int CompareTo(object obj) {
if (obj == null) return 1;
Person otherPerson = obj as Person;
if (otherPerson != null) return this.Name.CompareTo(otherPerson.Name);
else throw new ArgumentException("Object is not a Person");
}
}
위 코드에서 Person 클래스의 CompareTo 메서드는 먼저 대상 오브젝트가 null인지 확인하고, 그 다음 대상 오브젝트가 Person 타입인지 확인합니다. 만약 대상 오브젝트가 Person이라면, 이 메서드는 string 타입의 Name 프로퍼티를 비교하여 결과를 반환합니다.
IComparable 인터페이스를 구현하면 Array.Sort()나 List.Sort() 등의 메서드를 사용하여 오브젝트를 쉽게 정렬할 수 있습니다.
Visual Studio Code는 Unity에서 C# 파일을 편집하는 데 큰 도움이 될 수 있습니다. 모든 C# 기능이 지원되며 더 많은 기능이 있습니다. 아래 화면에서 코드 색상화, 괄호 매칭, 인텔리센스, 코드렌즈 등의 기능을 확인할 수 있습니다. 그리고 이것은 시작일 뿐입니다.
계속 읽어서 Unity와 프로젝트를 최상의 경험을 얻기 위해 어떻게 설정하는지 알아보세요.
Open upUnity Preferences,External Tools, then browse for the Visual Studio Code executable asExternal Script Editor.
The Visual Studio Code executable can be found at/Applications/Visual Studio Code.appon macOS,%localappdata%\Programs\Microsoft VS Code\Code.exeon Windows by default.
Unity has built-in support for opening scripts in Visual Studio Codeas an external script editor on Windows and macOS. Unity will detect when Visual Studio Code is selected as an external script editor and pass the correct arguments to it when opening scripts from Unity. Unity will also set up a default.vscode/settings.jsonwith file excludes, if it does not already exist (fromUnity 5.5 Release notes).
Since 2019.2, it is required to use theVisual Studio Code Editor package. The built-in support for opening scripts from Unity and gettingcsprojandslnfiles generated has been removed.
Unity hasa set of custom C# warnings, called analyzers, that check for common issues with your source code. These analyzers ship out of the box with Visual Studio but need to be set up manually in Visual Studio Code.
Due to how Unity handles its.csprojfiles, it does not seem possible to install packages automatically. You will need to download the analyzers from theNuGet websitemanually. Make sure to download the.nupkgfile, the source code from GitHub will not work.
When you're done, open the package file using a tool such as 7zip and extractMicrosoft.Unity.Analyzers.dllonto your project's root folder. You can place it inside a folder namedNuGet, for example. Do not place it insideAssetsorPackages, as that will cause Unity to try to process the.dll, which will make it output an error in the console.
Note: 7zip cannot open a.nupkgfile by right-click andOpen with. Instead, you have to open the 7zip application, navigate to the file, and then selectExtract.
Next, create anomnisharp.jsonfile at the root folder of your project, as explainedhere. Analyzer support in OmniSharp is experimental at the moment, so we need to enable it explicitly. We also need to point it to the.dllfile we just extracted.
Youromnisharp.jsonfile should end up looking like this:
where"./NuGet/microsoft.unity.analyzers.1.14.0/analyzers/dotnet/cs"is a relative path pointing to the folder containing the.dllfile. Depending on where you placed it, your path may look different.
The Unity analyzers should now be working in your project. You can test them by creating an emptyFixedUpdate()method inside one of yourMonoBehaviorclasses, which should trigger aThe Unity message 'FixedUpdate' is emptywarning (UNT0001).
Note that while it is possible to activate these analyzers, the suppressors they ship with the package (that turn off other C# warnings that may conflict with these custom ones) may not be picked up by OmniSharp at the moment,according to this thread. You can still turn off specific rules manually by following these steps:
Create a.editorconfigfile in your project's root folder (next to Unity's.csprojfiles).
root=truetells OmniSharp that this is your project root and it should stop looking for parent.editorconfigfiles outside of this folder.
dotnet_diagnostic.IDE0051.severity = noneis an example of turning off the analyzer with IDIDE0051by setting its severity level tonone. You can read more about these settings in theAnalyzer overview. You can add as many of these rules as you want to this file.
[*.cs]indicates that our custom rules should apply to all C# scripts (files with the.csextension).
You are now ready to code in Visual Studio Code, while getting the same warnings as you would when using Visual Studio!
You need to ensure that your solution is open in VS Code (not just a single file). Open the folder with your solution and you usually will not need to do anything else. If for some reason VS Code has not selected the right solution context, you can change the selected project by clicking on the OmniSharp flame icon on the status bar.
Choose the-CSharpversion of the solution file and VS Code will light up.
Unity creates a number of additional files that can clutter your workspace in VS Code. You can easily hide these so that you can focus on the files you actually want to edit.
To do this, add the following JSON to yourworkspace settings. By adding these excludes to your workspace settings, you will not change your global user settings and it allows anyone also working on the project to have the same file excludes.
As you can see below this will clean things up a lot...
Before
After
To edit this directly within VS Code Settings editor, go toFile>Preferences>Settings(Code>Preferences>Settingson macOS). Switch to theWorkspacetab and then type "files exclude" into the Settings editor search bar. Add a glob pattern similar to the pattern shown below by clicking theAdd Patternbutton for theFiles: Excludesetting. You will need to add each pattern separately.