I am having trouble initialising something before it gets used in a custom Editor.
I have a component attached to a game object, ResourceGenerator:
public class ResourceGenerator : MonoBehaviour {
//..some irrelevant public stuff here..
public List<string>[] resourceSpawnTimes; // This is what i intend to modify in a custom editor
void Awake() // I've also tried OnEnable
{
// MatchInfo is another component in another game object
MatchInfo info = (MatchInfo)GameObject.Find ("MatchInfo").GetComponent<MatchInfo>();
// Array size defined by variables set in editor for the MatchInfo object
resourceSpawnTimes = new List<string>[(int) (info.matchTimeSeconds / info.timeBetweenDropsSeconds)];
}
//..More irrelevant stuff..
}
The List[] resourceSpawnTimes
is what I want a custom editor interface for, so I’ve written ResourceSpawnTiming (It’s not neccessary to read through it all but I wanted to include something reasonably complete just in case):
[CustomEditor(typeof(ResourceGenerator))]
public class ResourceSpawnTiming : Editor {
MatchInfo info;
int minutes;
ResourceGenerator gen;
ser List<string>[] resourceSpawnTimes;
void OnEnable()
{
info = (MatchInfo)GameObject.Find("MatchInfo").GetComponent<MatchInfo>();
gen = (ResourceGenerator)target;
}
public override void OnInspectorGUI()
{
DrawDefaultInspector ();
minutes = (int)(info.matchTimeSeconds / info.timeBetweenDropsSeconds);
for(int i = 0; i < minutes; i++)
{
GUILayout.Label("Minutes into match: " + i + " - " + (i+1));
// Display check boxes for all the wood resources
foreach(string s in Resource.WoodResourceNames)
{
bool currentlyEnabled = GetCurrentValue(i,s);
SetCurrentValue( i, s, currentlyEnabled,
EditorGUILayout.Toggle(s, currentlyEnabled));
}
}
}
private bool GetCurrentValue(int minute, string resourceName)
{
// Check if resourceName is in the list for that minute
foreach(string s in gen.resourceSpawnTimes[minute]) // This is where resourceSpawnTimes turns out to still be null
{
if(s == resourceName)
return true; // resource currently enabled
}
return false; // resource not
}
private void SetCurrentValue(int minute, string resourceName, bool currentlyEnabled, bool enable)
{
//..Some stuff left out for brevity..
}
}
My problem is when I try to loop over resourceSpawnTimes
in ResourceSpawnTiming’s GetCurrentValue(..)
method. The gen object is not null but it’s List[] resourceSpawnTimes
is! As illustrated by this screenshot:
Having tested I now know that Awake()
, where resourceSpawnTimes
should be intialised, in the ResourceGenerator is not called before OnInspectorGUI()
in ResourceSpawnTimes, but I can’t figure out anyway to initialise it earlier! I also tried OnEnable() but that didn’t work either… I believe the issue is somewhat complicated by the fact I need to know what has been entered into the editor interface for MatchInfo before deciding on a size…
Been experimenting without any luck for hours, help much appreciated!