Download

Pass random by reference

If I want to have a seeded random (RandomStream) in my GameState blueprint, and use that to generate random numbers across multiple Actor blueprints, how could I accomplish that?

I added a getter in my GameState, but everything that gets the seed generates the same value. I want multiple Actors to query the same RandomStream instead.

I could of course wrap the various random functions and ask the GameState for anything random I need, GameState->GetIntegerInRange, GameState->GetRandomBool, etc… But that seems like a heavy-handed solution to the problem.

that seems pretty reasonable isn’t it?
i mean when you have a random stream, you get something like 0~1( or in c native 0 to max int).

so if you want to use this stream, you need to haveba interface to game state and different fuction interprete the value to give different output.

even if you eventually want to do it with C++, i think you’d still need to implement those.

There are already several functions available in blueprints that offer a random typed value of your choosing, and it appears that they come in pairs, one requiring a RandomStream input and one that does not. I’d just feel weird implementing wrappers around these functions in my GameState that are nothing more than wrappers around the seeded version.

yeah, that’s what i meant, you choose one and do other remapping out of the same source. i assume epic did what they did because of multithread reason, but it doesn’t really block you from implement one that gets from a single stream.

I think this is because by default structs (like RandomStream) are passed around ‘by value’, which means a copy is made, and so the copy of the stream is being updated rather than the original.

That’s exactly what I assumed, but that “by default” sounds interesting. Any way to change that behavior?

If you make a function that takes a RandomStream, you can select that parameter, open the Advanced settings and choose ‘by reference’.

That’s what I was looking for, thanks!

It looks like there’s not an option for returning a struct by reference though, is that the case?

When you pass in by reference, it is effectively an in-out parameter, you are expected to modify it within the function.

this is pretty interesting, is there any other similar functions behave in this way in UE4 currently?
As makeRandomStream does not have tool tip said about this, so can we assume other function will just making copies by default?
I guess random is probably more confusing for programmers in say C, but to think of it in function calls in graph makes sense that it’s a copy instead of setting seeds for a global stream like in C.