I’m having a problem with initializing a value in the unity editor.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using UnityEditor;
using UnityEditor.Callbacks;
using UnityEngine;
[CustomEditor(typeof(CombatAbility))]
public class CombatAbilityEditor : Editor
{
private static List<Type> combatAbilityComponentTypes = new List<Type>();
private CombatAbility combatAbilityData;
private bool showAddCombatAbilityComponentsButtons;
private void OnEnable()
{
combatAbilityData = target as CombatAbility;
}
public override void OnInspectorGUI()
{
base.OnInspectorGUI();
showAddCombatAbilityComponentsButtons = EditorGUILayout.Foldout(showAddCombatAbilityComponentsButtons, "Add Combat Ability Components");
if (showAddCombatAbilityComponentsButtons)
{
foreach (Type combatAbilityComponentType in combatAbilityComponentTypes)
{
if (GUILayout.Button(combatAbilityComponentType.Name))
{
CombatAbilityComponent combatAbilityComponent = Activator.CreateInstance(combatAbilityComponentType) as CombatAbilityComponent;
if (combatAbilityComponent == null)
{
Debug.LogError($"Tried to add Combat Ability Component of type \"{combatAbilityComponentType.Name}\", but failed to create instance.");
}
else
{
combatAbilityComponent.pertainedCombatAbility = combatAbilityData;
combatAbilityData.AddComponent(combatAbilityComponent);
EditorUtility.SetDirty(combatAbilityData);
}
}
}
}
}
[DidReloadScripts]
private static void OnRecompile()
{
Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
IEnumerable<Type> types = assemblies.SelectMany(assembly => assembly.GetTypes());
IEnumerable<Type> filteredTypes = types.Where(type => type.IsSubclassOf(typeof(CombatAbilityComponent)) && type.IsClass && !type.ContainsGenericParameters);
combatAbilityComponentTypes = filteredTypes.ToList();
}
}
I wrote a code like above, but the line 44(combatAbilityComponent.pertainedCombatAbility = combatAbilityData;) does not seem to work.
The above code actually runs, but the value is not initialized-probably gets reset- when the game starts running.
The value of ‘pertainedCombatAbility’ remains null.
To be more precise, each CombatAbility has CombatAbilityComponent such as DamageComponent, KnockbackComponent, StatusEffectComponent etc.
What I want to do in Line 44 is that I want each CombatAbilityComponents to have the information of what CombatAbility does they belong to.
When I write ‘Debug.Log("Pertained to: " + combatAbilityComponent.pertainedCombatAbility);’ below the Line 44, it prints out correct value in the console, but when the game starts, the value resets to null.
I can’t figure out what’s wrong with my code. Can anybody help? Thank you in advance.