I have an array of classes (Voxel) in a class. I use the following methods to add to and remove from the array. A memento pattern is used to store the action for each method so it can be undone/redone at any point.
public void AddVoxel(int x, int y, int z)
{
int index = z * width * height + y * width + x;
frames[currentFrame].Voxels[index] = new Voxel();
// Undo/Redo history
undoRedoHistories[currentFrame].Do(new AddMemento(index));
}
public void RemoveVoxel(int x, int y, int z)
{
int index = z * width * height + y * width + x;
// Undo/Redo history
undoRedoHistories[currentFrame].Do(new RemoveMemento(index, frames[currentFrame].Voxels[index]));
frames[currentFrame].Voxels[index] = null; // Does not update 'voxelSelected' reference
}
In a separate class I wish to have a reference to a particular voxel in the array of voxels held by the above class.
private Voxel voxelSelected = null;
As a reference type I would like this value to automatically know when the part of the array it “points” to holds a voxel or is null. This is important when using an undo command because a voxel can be removed from the array and become null, or vice versa.
To get a voxel from the array I use the following method.
public Voxel GetVoxel(int x, int y, int z)
{
return frames[currentFrame].Voxels[z * width * height + y * width + x];
}
I then set the reference to the voxel as follows.
public void SetVoxelSelected(ref Voxel voxel)
{
voxelSelected = voxel;
}
voxelMeshEditor.AddVoxel(0, 0, 0);
var voxel = voxelMeshEditor.GetVoxel(0, 0, 0); // Copies rather than references?
SetVoxelSelected(ref voxel);
Console.WriteLine(voxelSelected == null); // False
voxelMeshEditor.RemoveVoxel(0, 0, 0);
Console.WriteLine(voxelSelected == null); // False (Incorrect intended behaviour)
How can I correctly reference a voxel in the array so the voxelSelected value automatically updates when the array updates.
Don’t store a
Voxel, but store the coordinates you need to get the voxel.Instead of
have
giving