Unity prefab modification from sctipt

 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
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using BPMobile.Common.Extensions;
using UnityEditor;
using UnityEngine;
using Object = UnityEngine.Object;
public class StationPrefabComponentInjector : MonoBehaviour {
[SerializeField] private string _pathToPrefabs;
private void Start() {
for (int i = 1; i < 7; i++) {
string currentPath = _pathToPrefabs + i.ToString();
ModifyPrefabsInFolder(currentPath);
}
}
private void ModifyPrefabsInFolder(string folderPath) {
Debug.Log($"Modifying prefabs in folder: {folderPath}");
AssetDatabase.StartAssetEditing();
string[] guids = AssetDatabase.FindAssets(" t:GameObject", new string[] {folderPath});
foreach (string g in guids) {
string path = AssetDatabase.GUIDToAssetPath(g);
Object prefab = AssetDatabase.LoadAssetAtPath(path, typeof(GameObject));
GameObject prefabAsObject = prefab as GameObject;
PrefabModification(prefabAsObject);
}
AssetDatabase.StopAssetEditing();
AssetDatabase.SaveAssets();
}
private void PrefabModification(GameObject prefab) {
Regex prefabNameRegular = new Regex("^Station_");
if (!prefabNameRegular.IsMatch(prefab.name)) return;
Regex gameobjectToInjectRegular = new Regex("^StationWill");
ForAllChildrenRecursive(prefab.transform, x => {
if (!gameobjectToInjectRegular.IsMatch(x.name)) return;
if (x.GetComponent<StationBonusFXController>() == null) {
Debug.Log($"Modifying {prefab.name} prefab");
x.AddComponent<StationBonusFXController>();
}
});
}
private void ForAllChildrenRecursive(Transform parent, Action<GameObject> action) {
action(parent.gameObject);
foreach (Transform child in parent) {
ForAllChildrenRecursive(child, action);
}
}
}