-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLayersCodeGenerator.cs
More file actions
90 lines (79 loc) · 2.66 KB
/
Copy pathLayersCodeGenerator.cs
File metadata and controls
90 lines (79 loc) · 2.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#if UNITY_EDITOR
using System;
using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEditorInternal;
using UnityEngine;
[InitializeOnLoad]
static public class LayersCodeGenerator
{
static private string LayersFileName = @"Layers.cs";
[MenuItem("Tools/Generate Layers Constants")]
private static void Generate()
{
var filePath = GetFilePath();
if (string.IsNullOrEmpty(filePath))
{
filePath = Application.dataPath + $"/{LayersFileName}";
File.WriteAllText(filePath, "");
}
var content = File.ReadAllText(filePath);
var genContent = GenerateCode();
if (content != genContent)
{
File.WriteAllText(filePath, genContent);
var relativePath =
filePath.TrimStart(Application.dataPath.TrimEnd("Assets".ToCharArray()).ToCharArray());
AssetDatabase.ImportAsset(relativePath, ImportAssetOptions.ForceUpdate);
}
GC.Collect();
}
static string GetFilePath()
{
var assets = AssetDatabase.FindAssets("t:script Layers");
foreach(var asset in assets)
{
var path = AssetDatabase.GUIDToAssetPath(asset);
if ( Path.GetFileName(path) == "Layers.cs")
return path;
}
return null;
}
static string GenerateCode()
{
var fieldsCode = "";
List<string> layersAdded = new List<string>();
for (int i = 0; i < 32; i++)
{
var layerName = InternalEditorUtility.GetLayerName(i);
if( ! string.IsNullOrEmpty(layerName) )
{
layerName = layerName.Replace(" ", "_");
if(layersAdded.Contains(layerName) )
{
Debug.LogError($"Multiple layers with the same name. ({layerName})");
continue;
}
layersAdded.Add(layerName);
var layerCode = LayerIndexTemplate
.Replace(NameReplacer, layerName).Replace(ValueReplacer, i.ToString());
fieldsCode += layerCode;
}
}
var index = ClassTemplate.IndexOf("}");
return ClassTemplate.Insert(index, fieldsCode);
}
static string NameReplacer = "<name>";
static string ValueReplacer = "<value>";
static string ClassTemplate =
@"static public class Layers
{}
";
static string LayerIndexTemplate =
$@"
public const int {NameReplacer} = {ValueReplacer};
public const int {NameReplacer}Mask = 1 << {ValueReplacer};
";
}
#endif