I have a collection with objects of a type derived from ScriptableObject and I select a random element from it, using a random index:
public static T Random<T>(this IList<T> collection)
{
return collection[UnityEngine.Random.Range(0, collection.Count)];
}
Now comes the catch. I change the structure of the underlying collection type that holds my objects derived from ScriptableObject, which causes this randomized selection to return a different object, because the element at the index is a different object now, while the actual collection still holds the very same objects as before changing the structure.
To give an example, my list might be (A, B, C), with B being randomly selected at index 1, now I change my structure which causes the list to be sorted like (C, A, B), now A is selected at index 1, with the index not changing because the seed remains the same.
How do I change my random selection away from choosing a random index, allowing the internal collection structure to change, while still selecting the same object as before? In the example before, even after changing my structure, the same seed should still return B from the list, even though the internal list order changed.
It sounds like you’re doing some procedural generation, so the answer might be “you can’t”. To let your seed refer to the same object even after changing the structure, you have to have some map from index to object, and that map can’t change. Dictionary<int,SomeType> is a common way of mapping an id to an object so maybe that will hep you. For lists, the index or position in the list is a part of the structure, so if you change the structure, the index changes its meaning. There’s no avoiding that, but you can work around it like with the id->object dictionary idea.
Is there really no design for that? The idea about refering id to object does work, though, thank you!
To summarize my issue again, I have a collection of n values which doesn’t change. From this collection, I would like to choose an object randomly. This should always be the same object when using the same seed, independent from its index in the collection, under the constraint that the number of elements in the collection doesn’t change.
I thought about using GetHashCode() of the objects in the collection and somehow relating it to the seed, in some fancy way, but couldn’t really think about something straight away.