Component not added to model?
Ok, so I have a component that contains a data class. It looks something like this:
[Serializable]
public DataClass
{
public string someData = "";
public DataClass() {}
}
public class MyDataComponent : MonoBehaviour
{
public DataClass myData = new DataClass();
public void Update() {}
}
Now, I'm trying to add this component in the asset processor as certain models get imported.
void OnPostProcessModel(GameObject go)
{
MyDataComponent foo = go.GetComponent<MyDataComponent>();
if (foo == null)
{
foo = go.AddComponent<MyDataComponent>();
}
// assume we init foo with some data
}
public static void OnPostprocessAllAssets(string[] importedAssets, ...)
{
// assume we get the same asset as above
string modelPath = importedAssets[0];
GameObject model = (GameObject)PrefabUtility.InstantiatePrefab(AssetDatabase.LoadAssetAtPath(modelPath, typeof(GameObject)));
MyDataComponent foo = model.GetComponent<MyDataComponent>();
if (foo == null)
{
// FOO IS ALWAYS NULL
}
}
This seemed to work for me when the contents of DataClass were directly in MyDataComponent, but now that I've encapsulated them, suddenly it doesn't work again.
I can't figure out why the component returns null now when it was valid before.
Thoughts?
Answer by dmm_jbw · Apr 14, 2016 at 07:49 PM
Ok, got this sorted.
As it turns out there is nothing wrong with the code. The reason it worked before and then broken when I encapsulated the data is likely due to how Unity manages it's assets and stores things in its database.
The fix was to blow away the Library folder and let it rebuilt.
I had changed my script from being called DataClass to MyDataComponent and then created a new class called DataClass that was now inside MyDataComponent. This clearly messed with Unity's head!
Your answer
Follow this Question
Related Questions
How to create static component? 0 Answers
How to make RequireComponent list possible options. 1 Answer
accessing a script using a variable with getComponent, then accessing a variable inside that script 1 Answer
Public MonoBehavior string fields empty 0 Answers
How to automate removing non-MonoBehaviour derived scripts from a prefab 0 Answers