private bool OnGui_String(Rect position, SerializedProperty property, GUIContent label) { // InputAxisDataスクリプト自体生成されていないとこのスクリプトのコンパイルも通らないので // リフレクションでメンバ変数を取得する var field = m_InputAxisData.GetType().GetField("Config"); List <SystemDefines.InputAxis> inputAxes = field.GetValue(m_InputAxisData) as List <SystemDefines.InputAxis>; if (inputAxes == null) { return(false); } int selectIndex = 0; string[] inputAxisNames = new string[inputAxes.Count]; for (int i = 0; i < inputAxes.Count; ++i) { inputAxisNames[i] = (i + 1) + ": " + inputAxes[i].Name; if (property.stringValue != inputAxes[i].Name) { continue; } selectIndex = i; } selectIndex = EditorGUI.Popup(position, property.name, selectIndex, inputAxisNames); if (selectIndex < inputAxisNames.Length) { property.stringValue = inputAxes[selectIndex].Name; } return(true); }
public EditorActionNode(ScriptableObject nodeAsset, GraphNodeInfo nodeInfo, GraphNodeEditorInfo nodeEditorInfo, int index) { NodeAsset = nodeAsset; NodeInfo = nodeInfo; NodeEditorInfo = nodeEditorInfo; Index = index; RunningMarker = new VisualElement(); RunningMarker.style.width = 4f; titleContainer.hierarchy.Insert(0, RunningMarker); var infos = nodeAsset.GetType().GetCustomAttributes(typeof(NodeInfoAttribute), false); NodeInfoAttribute info; if (infos != null && infos.Length > 0) { info = (NodeInfoAttribute)infos[0]; title = info.Name; } else { title = nodeAsset.name; } var drawer = DefaultEditorNodeDraw.GetEditor(nodeAsset.GetType()); drawer.Create(this, nodeAsset); }
public static void LoadCompAssets(ScriptableObject ob) { FieldInfo[] fi = ob.GetType().GetFields(); FieldInfo fa = ob.GetType().GetField("compAssets"); List <string> ca = fa.GetValue(ob) as List <string>; int i = -1; foreach (FieldInfo f in fi) { if (!f.FieldType.IsSubclassOf(typeof(Component))) { continue; } i++; string s = ca[i]; if (s.Length == 0) { continue; } string sc = s.Substring(s.LastIndexOf("/") + 1); s = s.Substring(0, s.LastIndexOf("/")); GameObject g = GameObject.Find(s); f.SetValue(ob, g.GetComponent(sc)); } }
public static void SaveCompAssets(ScriptableObject ob) { FieldInfo[] fi = ob.GetType().GetFields(); FieldInfo fa = ob.GetType().GetField("compAssets"); List <string> ca = fa.GetValue(ob) as List <string>; ca.Clear(); foreach (FieldInfo f in fi) { if (!f.FieldType.IsSubclassOf(typeof(Component))) { continue; } Component c = f.GetValue(ob) as Component; if (c == null) { ca.Add(""); continue; } string s = c.gameObject.name + "/" + f.FieldType; Transform t = c.transform; while ((t = t.parent) != null) { s = t.gameObject.name + "/" + s; } ca.Add(s); } }
public static void Show(ScriptableObject scriptableObject) { if (scriptableObject.GetType() == typeof(SoldierConfig)) { current.tooltip = current.soldierTooltip; } else if (scriptableObject.GetType() == typeof(GeneralTooltipInfoConfig)) { current.tooltip = current.generalTooltip; } else if (scriptableObject.GetType() == typeof(TurretConfig)) { current.tooltip = current.turretTooltip; } else if (scriptableObject.GetType() == typeof(SpecialAttackConfig)) { current.tooltip = current.specialAttackTooltip; } else if (scriptableObject.GetType() == typeof(SkillTreeUpgradeConfig)) { current.tooltip = current.skillTreeTooltip; } else { return; } current.tooltip.SetContent(scriptableObject); current.tooltip.gameObject.transform.localScale = Vector3.zero; current.tooltip.gameObject.SetActive(true); LeanTween.scale(current.tooltip.gameObject, Vector3.one, 0.5f).setEaseOutBack().setIgnoreTimeScale(true); }
/// <summary> /// Given a service type, finds all sub-classes of BaseMixedRealityProfile that are /// designed to configure that service. /// </summary> public static IReadOnlyCollection <Type> GetProfileTypesForService(Type serviceType) { if (serviceType == null) { return(Array.Empty <Type>()); } Type[] types; if (!profileTypesForServiceCaches.TryGetValue(serviceType, out types)) { HashSet <Type> allTypes = new HashSet <Type>(); ScriptableObject[] allProfiles = GetProfilesOfType(typeof(BaseMixedRealityProfile)); for (int i = 0; i < allProfiles.Length; i++) { ScriptableObject profile = allProfiles[i]; if (IsProfileForService(profile.GetType(), serviceType)) { allTypes.Add(profile.GetType()); } } types = allTypes.ToArray(); profileTypesForServiceCaches.Add(serviceType, types); } return(types); }
public void InsertSingleton() { if (SingletonToAdd) { AddSingleton(SingletonToAdd.GetType(), SingletonToAdd); SingletonToAdd = null; } }
private static ScriptableObject CloneReferencedPlayableAsset(ScriptableObject original, PlayableDirector directorInstance) { ScriptableObject scriptableObject = Object.Instantiate <ScriptableObject>(original); if (scriptableObject == null || !(scriptableObject is IPlayableAsset)) { throw new InvalidCastException("could not cast instantiated object into IPlayableAsset"); } if (directorInstance != null) { SerializedObject serializedObject = new SerializedObject(original); SerializedObject serializedObject2 = new SerializedObject(scriptableObject); SerializedProperty iterator = serializedObject.GetIterator(); if (iterator.Next(true)) { do { serializedObject2.CopyFromSerializedProperty(iterator); }while (iterator.Next(false)); } serializedObject2.ApplyModifiedProperties(); EditorUtility.SetDirty(directorInstance); } if (directorInstance != null) { List <FieldInfo> list = (from f in scriptableObject.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) where f.FieldType.IsGenericType && f.FieldType.GetGenericTypeDefinition() == typeof(ExposedReference) select f).ToList <FieldInfo>(); foreach (FieldInfo current in list) { object value = current.GetValue(scriptableObject); FieldInfo field = value.GetType().GetField("exposedName"); if (field != null) { PropertyName propertyName = (PropertyName)field.GetValue(value); bool flag = false; Object referenceValue = directorInstance.GetReferenceValue(propertyName, ref flag); if (flag) { PropertyName propertyName2 = new PropertyName(GUID.Generate().ToString()); directorInstance.SetReferenceValue(propertyName2, referenceValue); field.SetValue(value, propertyName2); } } current.SetValue(scriptableObject, value); } } IEnumerable <FieldInfo> enumerable = from f in scriptableObject.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) where !f.IsNotSerialized && f.FieldType == typeof(AnimationClip) select f; foreach (FieldInfo current2 in enumerable) { current2.SetValue(scriptableObject, TimelineHelpers.CloneAnimationClipIfRequired(current2.GetValue(scriptableObject) as AnimationClip, original)); } return(scriptableObject); }
public void pressed() { MethodInfo Press = Script.GetType().GetMethod("pressed"); if (Press != null) { Press.Invoke(Script, null); } }
PostProcessingModelFake AddModel(string name, ScriptableObject profile) { if (profile == null) { return(null); } var result = GetPostprocessingModel(name, profile); if (result == null) { if (AddSettings == null) { AddSettings = profile.GetType().GetMethods((BindingFlags)int.MaxValue).FirstOrDefault(m => m.Name == "AddSettings" && m.GetParameters().Length == 1 && m.GetParameters()[0].ParameterType == typeof(Type)); } if (AddSettings == null) { throw new Exception("Cannot find AddSettings method"); } AddSettings.Invoke(profile, new[] { Params.GetTypeFromStringName(name) }); } result = GetPostprocessingModel(name, profile); result.enabled = true; if (name == EFFECTS.ColorGrading) { result.GRADING_MODE = VARIABLES.LowDefinitionRange; } return(result); }
/// <summary> /// Creates, saves, and then opens a new asset for the target <see cref="ScriptableObject"/>. /// </summary> /// <param name="scriptableObject"><see cref="ScriptableObject"/> you want to create an asset file for.</param> /// <param name="path">Optional path for the new asset.</param> /// <param name="fileName">Optional filename for the new asset.</param> public static ScriptableObject CreateAsset(this ScriptableObject scriptableObject, string path = null, string fileName = null) { var name = string.IsNullOrEmpty(fileName) ? $"{scriptableObject.GetType().Name}" : fileName; if (string.IsNullOrEmpty(path)) { path = "Assets"; } if (Path.GetExtension(path) != string.Empty) { var subtractedPath = path.Substring(path.LastIndexOf("/", StringComparison.Ordinal)); path = path.Replace(subtractedPath, string.Empty); } if (!Directory.Exists(Path.GetFullPath(path))) { Directory.CreateDirectory(Path.GetFullPath(path)); } string assetPathAndName = AssetDatabase.GenerateUniqueAssetPath($"{path}/{name}.asset"); AssetDatabase.CreateAsset(scriptableObject, assetPathAndName); AssetDatabase.SaveAssets(); AssetDatabase.Refresh(); EditorUtility.FocusProjectWindow(); Selection.activeObject = scriptableObject; EditorGUIUtility.PingObject(scriptableObject); return(scriptableObject); }
static ScriptableObject SaveScriptableAsset(ScriptableObject asset, string path) { CreateDirByAssetPath(path); bool exist = true; var obj = AssetDatabase.LoadAssetAtPath <ScriptableObject>(path); if (obj == null) { exist = false; obj = ScriptableObject.CreateInstance(asset.GetType().Name); } if (!exist) { EditorUtility.CopySerialized(asset, obj); RemapObject(obj, path); AssetDatabase.CreateAsset(obj, path); AssetDatabase.Refresh(); return(AssetDatabase.LoadAssetAtPath <ScriptableObject>(path)); } else { return(obj); } }
private void CreateEditor(ScriptableObject targetObject, SerializedProperty property, int index = -1) { var targetObjectType = targetObject.GetType(); if (!_editorTypes.TryGetValue(targetObjectType, out var editorType)) { editorType = typeof(HiraCollectionTargetDefaultEditor); } var editor = (HiraCollectionTargetBaseEditor)Activator.CreateInstance(editorType); editor.Init(targetObject, _editor); editor.OnEnable(); editor.BaseProperty = property.Copy(); if (index < 0) { _editors.Add(editor); } else { _editors[index] = editor; } editor.BaseProperty.isExpanded = true; }
private void SerializeScriptableObject(int assetId, ScriptableObject scriptableObject, List <ScriptableObjectData> outputList) { var type = scriptableObject.GetType(); var fields = GetSerializeableFields(type); if (!fields.Any()) { return; } var data = new ScriptableObjectData { Name = scriptableObject.name, Id = assetId, }; outputList.Add(data); foreach (var f in fields) { var value = f.GetValue(scriptableObject); var jsonValue = JsonConvert.SerializeObject(value, Formatting.None, mJsonSettings); data.Fields.Add(new FieldData() { Name = f.Name, Json = jsonValue, }); } }
/// <summary> /// Create scriptable object asset and save it on disk /// </summary> /// <param name="scriptableObject"></param> /// <param name="path">Relative path in assets folder</param> /// <param name="fileName">Filename without extension (it is always .asset)</param> /// <returns>The same scriptable object</returns> public static ScriptableObject CreateAsset(ScriptableObject scriptableObject, string path = null, string fileName = null) { var name = string.IsNullOrEmpty(fileName) ? scriptableObject.GetType().Name : fileName; if (string.IsNullOrEmpty(path)) { path = "Assets"; } if (Path.GetExtension(path) != string.Empty) { var subtractedPath = path.Substring(path.LastIndexOf("/", StringComparison.Ordinal)); path = path.Replace(subtractedPath, string.Empty); } if (!Directory.Exists(Path.GetFullPath(path))) { Directory.CreateDirectory(Path.GetFullPath(path)); } string assetPathAndName = UnityEditor.AssetDatabase.GenerateUniqueAssetPath(path + "/" + name + ".asset"); UnityEditor.AssetDatabase.CreateAsset(scriptableObject, assetPathAndName); UnityEditor.AssetDatabase.SaveAssets(); UnityEditor.AssetDatabase.Refresh(); return(scriptableObject); }
static void OnUpdate() { // Relying on the fact that toolbar is ScriptableObject and gets deleted when layout changes if (m_currentToolbar == null) { // Find toolbar var toolbars = Resources.FindObjectsOfTypeAll(m_toolbarType); m_currentToolbar = toolbars.Length > 0 ? (ScriptableObject)toolbars[0] : null; if (m_currentToolbar != null) { #if UNITY_2021_1_OR_NEWER var root = m_currentToolbar.GetType().GetField("m_Root", BindingFlags.NonPublic | BindingFlags.Instance); var rawRoot = root.GetValue(m_currentToolbar); var mRoot = rawRoot as VisualElement; RegisterCallback("ToolbarZoneLeftAlign", OnToolbarGUILeft); RegisterCallback("ToolbarZoneRightAlign", OnToolbarGUIRight); void RegisterCallback(string root, Action cb) { var toolbarZone = mRoot.Q(root); var parent = new VisualElement() { style = { flexGrow = 1, flexDirection = FlexDirection.Row, } }; var container = new IMGUIContainer(); container.onGUIHandler += () => { cb?.Invoke(); }; parent.Add(container); toolbarZone.Add(parent); } #else #if UNITY_2020_1_OR_NEWER var windowBackend = m_windowBackend.GetValue(m_currentToolbar); // Get it's visual tree var visualTree = (VisualElement)m_viewVisualTree.GetValue(windowBackend, null); #else // Get it's visual tree var visualTree = (VisualElement)m_viewVisualTree.GetValue(m_currentToolbar, null); #endif // Get first child which 'happens' to be toolbar IMGUIContainer var container = (IMGUIContainer)visualTree[0]; // (Re)attach handler var handler = (Action)m_imguiContainerOnGui.GetValue(container); handler -= OnGUI; handler += OnGUI; m_imguiContainerOnGui.SetValue(container, handler); #endif } } }
void IPreprocessBuildWithReport.OnPreprocessBuild(BuildReport report) { objects.Clear(); names.Clear(); preloadedAssets.Clear(); objects.Add(ALESettings.Get()); names.Add(ALESettings.Get().SettingName); preloadedAssets.AddRange(PlayerSettings.GetPreloadedAssets()); for (int i = 0; i < objects.Count; i++) { if (File.Exists($"{ProjectSettingsConsts.ROOT_FOLDER}/{names[i]}.asset")) { ScriptableObject setting = objects[i]; string assetPath = $"Assets/{ProjectSettingsConsts.PACKAGE_NAME}_{names[i]}.asset"; setting.hideFlags = HideFlags.None; AssetDatabase.CreateAsset(setting, assetPath); AssetDatabase.Refresh(ImportAssetOptions.ForceUpdate); Object newAsset = AssetDatabase.LoadAssetAtPath(assetPath, setting.GetType()); preloadedAssets.Add(newAsset); } } PlayerSettings.SetPreloadedAssets(preloadedAssets.ToArray()); }
private static void OnScriptsReload() { if (!EditorPrefs.HasKey("NotionAPI_DatabaseName")) { return; } string className = EditorPrefs.GetString("NotionAPI_DatabaseName"); string path = EditorPrefs.GetString("NotionAPI_DatabasePath"); int schemaInstanceId = EditorPrefs.GetInt("NotionAPI_DatabaseSchemaId"); EditorPrefs.DeleteKey("NotionAPI_DatabaseName"); EditorPrefs.DeleteKey("NotionAPI_DatabasePath"); EditorPrefs.DeleteKey("NotionAPI_DatabaseSchemaId"); var schema = EditorUtility.InstanceIDToObject(schemaInstanceId); ScriptableObject so = CreateInstance(className); so.name = className; so.GetType().GetField("databaseSchema").SetValue(so, schema); AssetDatabase.CreateAsset(so, path + ".asset"); AssetDatabase.SaveAssets(); }
public void Migrate() { SerializedObject serObj = new SerializedObject(monoBehaviour); SerializedProperty prop = serObj.GetIterator(); while (prop.NextVisible(true)) { FieldInfo monoBehaviourFieldInfo = monoBehaviour.GetType().GetField(prop.name, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public); if (monoBehaviourFieldInfo != null) { Debug.LogFormat("Migrating {0} ...", monoBehaviourFieldInfo); FieldInfo scriptableObjectFieldInfo = scriptableObject.GetType().GetField(prop.name, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public); if (scriptableObjectFieldInfo == null) { Debug.LogWarningFormat("There was no field {0}. Continuing...", monoBehaviourFieldInfo); } else { object data = monoBehaviourFieldInfo.GetValue(monoBehaviour); Debug.LogFormat("Setting data {0} to scriptable object {1}", data, scriptableObject); scriptableObjectFieldInfo.SetValue(scriptableObject, data); } } } EditorUtility.SetDirty(scriptableObject); }
/// <summary>Starts a coroutine.</summary> /// <param name="target">Reference to the instance of the class containing the method.</param> /// <param name="methodName">The name of the coroutine method to start.</param> /// <param name="value">The parameter to pass to the coroutine.</param> public EditorCoroutine StartCoroutine(ScriptableObject target, string methodName, object value) { MethodInfo methodInfo = target.GetType() .GetMethod(methodName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); if (methodInfo == null) { Debug.LogError("Coroutine '" + methodName + "' couldn't be started, the method doesn't exist!"); } object returnValue; if (value == null) { returnValue = methodInfo.Invoke(target, null); } else { returnValue = methodInfo.Invoke(target, new object[] { value }); } if (returnValue is IEnumerator) { return(StartCoroutine(target, (IEnumerator)returnValue)); } else { Debug.LogError("Coroutine '" + methodName + "' couldn't be started, the method doesn't return an IEnumerator!"); } return(null); }
/// <summary> /// Draws the node contents /// </summary> public virtual void DrawContent() { if (_Content == null) { GUILayout.FlexibleSpace(); GUILayout.Label("No content", NodeEditorStyle.NodeText); GUILayout.FlexibleSpace(); } else { GUILayout.FlexibleSpace(); string lTitle = ""; NodeContent lContent = _Content as NodeContent; if (lContent != null) { lTitle = lContent.Name; } if (lTitle.Length == 0) { lTitle = BaseNameAttribute.GetName(_Content.GetType()); } GUILayout.Label(lTitle, NodeEditorStyle.NodeText); GUILayout.FlexibleSpace(); } }
void EditorSkinsDropdown(Rect pos) { string[] guids = AssetDatabase.FindAssets("t:ScriptableObject"); List <EditorSkin> skins = new List <EditorSkin>(); for (int g = 0; g < guids.Length; g++) { ScriptableObject obj = AssetDatabase.LoadAssetAtPath <ScriptableObject>(AssetDatabase.GUIDToAssetPath(guids[g])); if (obj != null && obj.GetType().Equals(typeof(EditorSkin))) { skins.Add((EditorSkin)obj); } } skins.Sort((x, y) => x.orderValue.CompareTo(y.orderValue)); GenericMenu menu = new GenericMenu(); for (int t = 0; t < skins.Count; t++) { EditorSkin skin = skins[t]; menu.AddItem(new GUIContent(skin.title), EditorSettings.INSTANCE.editorSkin == skin, delegate() { EditorSettings.INSTANCE.editorSkin = skin; EditorUtility.SetDirty(EditorSettings.INSTANCE); AbilityDesignerWindow.OrderSkinChange(); Focus(); }); } menu.DropDown(pos); }
public static void Catch(string id, ScriptableObject data) { if (data != null) { Catch(id, data.GetType().FullName, JsonUtility.ToJson(data)); } }
protected override void AllocateData(ref BlobBuilder builder, ref BlobVariable <T> blobVariable, INodeDataBuilder self, ITreeNode <INodeDataBuilder>[] tree) { var type = ScriptableObject.GetType(); FieldInfo fieldInfo = null; PropertyInfo propertyInfo = null; if (ScriptableObject != null) { fieldInfo = type.GetField(ScriptableObjectValueName, FIELD_BINDING_FLAGS); } if (fieldInfo == null) { propertyInfo = type.GetProperty(ScriptableObjectValueName, FIELD_BINDING_FLAGS); } if ((fieldInfo == null || fieldInfo.FieldType != typeof(T)) && (propertyInfo == null || !propertyInfo.CanRead || propertyInfo.PropertyType != typeof(T))) { Debug.LogError($"{ScriptableObject.name}.{ScriptableObjectValueName} is not valid"); throw new ArgumentException(); } var value = fieldInfo?.GetValue(ScriptableObject) ?? propertyInfo?.GetValue(ScriptableObject); builder.Allocate(ref blobVariable, (T)value); }
public IntPtr Allocate(ref BlobBuilder builder, ref BlobVariant blobVariant) { blobVariant.VariantId = GuidHashCode(GUID); var type = ScriptableObject.GetType(); FieldInfo fieldInfo = null; PropertyInfo propertyInfo = null; if (ScriptableObject != null) { fieldInfo = type.GetField(ScriptableObjectValueName, BindingFlags.Instance | BindingFlags.Public); } if (fieldInfo == null) { propertyInfo = type.GetProperty(ScriptableObjectValueName, BindingFlags.Instance | BindingFlags.Public); } if ((fieldInfo == null || fieldInfo.FieldType != typeof(T)) && (propertyInfo == null || !propertyInfo.CanRead || propertyInfo.PropertyType != typeof(T))) { Debug.LogError($"{ScriptableObject.name}.{ScriptableObjectValueName} is not valid"); throw new ArgumentException(); } var value = fieldInfo?.GetValue(ScriptableObject) ?? propertyInfo?.GetValue(ScriptableObject); return(builder.Allocate(ref blobVariant, (T)value)); }
/// <summary> /// 日志输出(致命日志) /// </summary> /// <param name="iScript">当前脚本</param> /// <param name="iFormat">日志格式</param> /// <param name="iArgs"></param> public static void Fatal(this ScriptableObject iScript, string iFormat, params object[] iArgs) { var className = iScript.GetType().Name; var log = string.Format(iFormat, iArgs); Loger.Fatal($"[{className}] {log}"); }
bool CheckSelectedObject() { if (Selection.activeObject == null || !(Selection.activeObject is ScriptableObject)) { return(false); } ScriptableObject so = Selection.activeObject as ScriptableObject; graphList = new Dictionary <string, GraphData>(); foreach (FieldInfo fieldInfo in so.GetType().GetFields()) { GraphData data; if (GraphData.CanCreateGraphData(so, fieldInfo, out data)) { string uniqueName = data.PropertyName; int i = 0; while (graphList.Keys.Contains(uniqueName)) { uniqueName = data.PropertyName + " [" + (++i) + "]"; } graphList.Add(uniqueName, data); } } //return nodes.Count > 0; return(true); }
void AllScriptableObjectUpdate() { string[] Files = Directory.GetFiles(scriptableObjectDir); try { for (int i = 0; i < Files.Length; ++i) { string extension = Path.GetExtension(Files[i]); if (extension == ".meta") { continue; } string fileName = Path.GetFileNameWithoutExtension(Files[i]); ScriptableObject scriptableObject = ResourceLoader.Load <ScriptableObject>(string.Format("ScriptableObject/{0}.asset", fileName)); Type scriptableType = scriptableObject.GetType(); if (scriptableType != null && scriptableType.FullName.Contains("ExcelDataClass")) { MethodInfo methodInfo = scriptableType.GetMethod("Load"); if (methodInfo != null) { methodInfo.Invoke(scriptableObject, null); Debug.LogError("Load!!: " + scriptableType.Name); } } } } catch (Exception e) { Debug.LogError("e : " + e); } }
public EditorNodeElement(ScriptableObject so, EditorActionNode node) { _so = so; _node = node; _typeInfo = NodeTypeInfo.GetNodeTypeInfo(so.GetType()); CreateFieldElement(); }