I have a Сharacter class with a PositionOnGrid property that stores the Cell component
public class Character
{
public Cell PositionOnGrid;
}
Сharacter - it's just capsule mesh saved like prefab, i have this prefab instance on the scene.
Cell - the same with hexagonal mesh. Saved like prefab, i have many of this on the scene.
Picture
I'm trying to create a tool for conveniently placing objects on a grid in the Editor. Therefore, there is another script on the Character object that updates the PositionOnGrid and snap transform.position when I move the object on the stage.
[ExecuteAlways]
public class CharacterEditorMode : MonoBehaviour
{
private Character _selfCharacter;
private Raycaster _raycaster;
private void Awake()
{
_selfCharacter = this.GetComponent<Character>();
_raycaster = new Raycaster();
}
private void Update()
{
if (Application.isPlaying)
return;
if (transform.hasChanged)
{
UpdateCoordinates();
transform.hasChanged = false;
}
}
private void UpdateCoordinates()
{
if (_raycaster.CastRayDownOnCellLayer(_selfCharacter.transform.position + new Vector3(0, 0.1f, 0)))
{
GameObject cellObject = _raycaster.GetRayHitObject();
Cell cellComponent = cellObject.GetComponent<Cell>();
_selfCharacter.transform.position = cellObject.transform.position;
_selfCharacter.PositionOnGrid = cellComponent;
}
}
}
Now it works in the editor, but when I run PlayMode, the prefab settings such as PositionOnGrid are reset to the default values from the prefab.(Picture)
They are marked in bold as edited, but I cannot apply the changes to the prefab, since I need many instances with different settings.
I tried PrefabUtility.RecordPrefabInstancePropertyModifications |
Undo.RecordObject |
EditorUtility.SetDirty |
[SerializeField] tag
This did not give the desired result. Maybe I'm using these things wrong? By the way, prefab settings are saved on the stage even when the project is restarted. The problem occurs exactly when starting PlayMode.
If I remove the Application.isPlaying in Update() it seems to work. But this interferes with other methods for moving a character already within the game. This should only work in the editor.
if (Application.isPlaying)
return;
If I set properties manually with hands, for example Cell, it is saved in PlayMod