- Home /
Set Variable on Editor Save - Load in Game?
I would like to bake pathing data into terrain in my game automatically. Whenever the terrain is saved in the editor, I would like to automatically calculate new pathing data and assign it to the terrain so that it can be accessed when my game starts.
To do this, I wrote a class called Pathing
which is a MonoBehavior
so can be assigned as a component
to a GameObject
:
public class Pathing : MonoBehaviour {
public uint[,] height;
void Start () {
print("I have a height array: " + height[0, 0].ToString());
}
}
Then I have another called class called PathingGenerator
which inherits from AssetModificationProcessor
so that it will see when files are saved, which will be the queue to update the data in Pathing
.
using UnityEditor;
using UnityEngine;
using System.Collections;
public class PathingGenerator : UnityEditor.AssetModificationProcessor {
public static string[] OnWillSaveAssets(string[] paths) {
// Find the terrain
Terrain[] terrains = Object.FindObjectsOfType<Terrain>();
if (terrains.Length != 1) {
Debug.LogError("There should be exactly 1 terrain - " + terrains.Length.ToString() + " found.");
return paths;
}
// Ensure this component exists.
Pathing[] pathings = terrains[0].gameObject.GetComponents<Pathing>();
Pathing pathing;
if (pathings.Length == 0) {
pathing = terrains[0].gameObject.AddComponent<Pathing>();
Debug.Log("Just added.");
} else {
pathing = pathings[0];
Debug.Log("Already existed.");
}
// Set the values - for now, to test this works, just use fixed numbers.
// In the future I'll have actual complex equations that run here.
pathing.height = new uint[2, 2];
pathing.height[0, 0] = 0;
pathing.height[0, 1] = 1;
pathing.height[1, 0] = 2;
pathing.height[1, 1] = 3;
Debug.Log("They are set.");
return paths;
}
}
After I save and before I run, this is printed out in the log:
Already existed.
They are set.
When I run, I get this message:
NullReferenceException: Object reference not set to an instance of an object
Pathing.Start () (at Assets/Scripts/Pathing.cs:10)
What am I doing wrong? Is there a better way to do what I want? (I don't want to run my equations within the game itself. They involve a lot of floating point math which ultimately gets rounded to ints. This potentially will cause massive issues if different platforms have slightly different numbers, which will result in pathing maps that are completely different on each platform. I want to guarantee that they're identical everywhere, thus I'd like to bake the integers into the terrain from someplace within the Editor.)
I believe the problem may be that uint[,]
is not serializable. This brings me now to the question: what is and isn't serializable, and what is my best course of action now? It appears I can use a uint[]
... coupling that with a uint representing length and/or width may make this easy...
Your answer
