In Unity 2018.3, I need to dynamically add certain components to a non-instantiated GameObject (Prefab), at runtime. I need to add it to the prefab, because the GameObject itself is then instantiated in different places.
To do this I use this code:
public class Initialiser : MonoBehaviour
{
[SerializeField]
GameObject prefab;
void Awake(){
prefab.AddComponent<myComponent>();
}
}
This actually works, and the prefab, when instantiated in other places, comes with the component attached.
BUT, it also yields this error:
Assertion failed on expression: '!go.TestHideFlag(Object::kNotEditable)' UnityEngine.GameObject:AddComponent()
The error does not seem to hinder the intended behavior, but I don’t know if it has other implications.
I found here that this error is linked to the new 2018.3 Prefab framework, and that components should now be added using PrefabUtility.LoadPrefabContents. The problem is that this solution only works in the editor, and will not work at runtime.
Any idea how to solve this?
I will repeat what Unity folks have been posting all over the forum:
Prefabs do not exist at runtime. so at runtime you can’t change prefabs as they do not exist in that environment.
Why are you trying to edit prefabs at runtime? Can you elaborate a bit more on what you are trying to achieve and maybe can be of more help on that part 