• Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
Question by Doeko · Sep 09, 2013 at 11:56 AM · c#filesasset path

C# find class file path for any class

I have looked all over for t$$anonymous$$s, but to no avail.

What I want to do is the following: determine the path of the class file in w$$anonymous$$ch to find a specified C# class (non-monobehaviour/ScriptableObject). I already know how to find monobehaviour scripts.

I've looked on the C# boards but it is mostly concerned with how to find a class library (.dll) w$$anonymous$$ch contains a certain class. It's probably not a situation that happens outside of t$$anonymous$$s environment.

Comment

People who like this

0 Show 2
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image AndyMartin458 · Sep 09, 2013 at 02:55 PM 0
Share

You can get the path to the assets folder by Application.DataPath . Through that, you could find your path. If you have a good naming convention like Assets_ThisType_ThatType, then you could parse the class name to assemble the rest of the path from the Application.DataPath folder.

I guess this would only work in the editor though where the files are in that location.

avatar image Doeko AndyMartin458 · Sep 09, 2013 at 03:02 PM 0
Share

The solution can't rely on conventions like that. I've already found a solution which I will post to the stackoverflow later (it will be using filesystem searches and possibly text searches through the class files)

On a sidenote .js files (which I am unfamiliar with unforunately) seem to always have the same name as the class they represent, so that makes those easier to find.

2 Replies

· Add your reply
  • Sort: 
avatar image
Best Answer

Answer by Doeko · Sep 09, 2013 at 12:24 PM

I realized t$$anonymous$$s is more a .net issue than a Unity issue and goes beyond the scope of Unity Answers. Relisted the question here..

http://stackoverflow.com/questions/18697865/find-a-class-its-cs-file-in-project

Comment
clunk47

People who like this

1 Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Doeko · Sep 11, 2013 at 10:49 AM 0
Share

Added an answer with code example

avatar image

Answer by PanopticMedia · 3 days ago

Here in 2023. I offer my code as another solution to this problem. You will require a few code analysis Dlls, but so far it works great and allowed me to open C# files directly from a right-click menu. I have something like 80-100 .cs files in my project and no SSD on the machine I'm using. Generally runs in about 1/4 of a second, but you could probably optimize if you want. I'm not sure what it does with generics, I haven't tested that.

 /// <summary>
 /// Utility class for code analysis.
 /// </summary>
 public static class CodeAnalysis
 {
     private static Dictionary<string, string> ClassNameToFileMapping = new Dictionary<string, string>();

     /// <summary>
     /// When this class is first loaded, we'll compile a list of all classes.
     /// </summary>
     static CodeAnalysis()
     {
         string[] cSharpFiles = Directory.GetFiles(Application.dataPath, "*.cs", SearchOption.AllDirectories);
         foreach (string cSharpFile in cSharpFiles)
         {
             SyntaxTree syntaxTree = CSharpSyntaxTree.ParseText(File.ReadAllText(cSharpFile));
             var root = syntaxTree.GetCompilationUnitRoot();
             foreach (SyntaxNode node in root.DescendantNodes())
             {
                 if (node is TypeDeclarationSyntax syntaxNode)
                 {
                     string fullname = syntaxNode.Identifier.ValueText;
                     IEnumerable<SyntaxNode> parentsAndSelf = syntaxNode.AncestorsAndSelf().Where(node => node is TypeDeclarationSyntax || node is NamespaceDeclarationSyntax);
                     StringBuilder stringBuilder = new StringBuilder();

                     bool typeEncountered = false;
                     bool anyEncountered = false;
                     foreach (SyntaxNode nameBuilderNode in parentsAndSelf.Reverse())
                     {
                         switch (nameBuilderNode)
                         {
                             case TypeDeclarationSyntax typeSyntax:
                                 if (typeEncountered) stringBuilder.Append("+");
                                 else if (anyEncountered) stringBuilder.Append(".");

                                 // Appending the type name
                                 stringBuilder.Append(typeSyntax.Identifier.ValueText);

                                 typeEncountered = true;
                                 break;
                             case NamespaceDeclarationSyntax namespaceSyntax:
                                 if (anyEncountered) stringBuilder.Append(".");

                                 // appending the namespace name
                                 stringBuilder.Append(namespaceSyntax.Name.GetText());

                                 break;
                             default:
                                 break;
                         }

                         anyEncountered = true;
                     }

                     // The carriage return can sometimes end up here. Need to remove it.
                     string className = stringBuilder.ToString().Replace("\r\n", "");

                     // We have to do this check for partial classes.
                     if (!ClassNameToFileMapping.ContainsKey(className))
                     {
                         ClassNameToFileMapping.Add(className, cSharpFile);
                     }
                 }
             }
         }
     }

     /// <summary>
     /// Get a file for a type.
     /// </summary>
     public static string GetFileForType(Type type)
     {
         return ClassNameToFileMapping[type.FullName];
     }

     public static string GetAssetPathForType(Type type)
     {
         string filePath = GetFileForType(type);
         string assetPath = "Assets" + filePath.Substring(Application.dataPath.Length);
         return assetPath;
     }
 }
Comment

People who like this

0 Show 0 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Follow this Question

Answers Answers and Comments

18 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Multiple Cars not working 1 Answer

Distribute terrain in zones 3 Answers

How to copy Files external to Game application to Application.dataPath 1 Answer

Will System.IO.File work on Macs 2 Answers

Flip over an object (smooth transition) 3 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges