I’m trying to build an editor utility widget that can swap the locations of static meshes within a level at random.
What’s the best way to do this?
I can do it with just two objects. I cache the locations of each object and then set object A to object Bs location.
But confused about how to do more than 2 and at random locations so, the first time object A swaps location with object B but the 2nd time object A swaps with object C.
After trying your solution pezzott1, it works perfectly. I’m trying to figure out how it works though. If you could please explain it some more that would be great for my learning.
The way I understand you are caching the first location of item 0 in the array and then looping through the objects. You then add to the array index, so if we are on object 0 the array index will be 1 so the new location of object 0 will be the location of item 1. And because you are shuffling the array every time then this means that the objects at locations 0 and 1 will be different each time.
Does the false part of the branch make sure we set the location of the last object as we would be passed the bounds of the array? Because otherwise the last object won’t be set to anything?
Think you got the idea. The logic is from a fun exercise with the objective of shifting values in an array without duplicating it.
Might be easier to illustrate in cpp:
.cpp
void AShiftArray::ShiftArrayLeft(TArray<int32>& Array)
{
// Store value of first index because it will be overwritten.
int32 FirstValue = Array[0];
// Get last valid index of array.
size_t LastIndex = (Array.Num() - 1);
// Loop through array from 0 -> LastIndex
for (size_t i = 0; i <= LastIndex; ++i)
{
/**
* Know when its at last index.
** True: Assign value of next index to current:
*** 0 <- 1
*** 1 <- 2
*** 2 <- 3...
** False: Assign FirstValue to last valid index.
*/
(i != LastIndex) ? Array[i] = Array[(i + 1)] : Array[i] = FirstValue;
}
}
Notice how index 0 gets overriden first, so we store it to apply to the last index after the last - 1 is assigned the value of the last.
In blueprint the only difference is that i fed it a shuffled array. Keeping the array in order would just move the boxes to the left (and first to last). For example: