I’m trying to to add a buffer to my jump input on my game and I wan to use function because to code will be the same ever time, the only change will be how long the buffer will last (bufferLength) and the buffer variable (buffer) but I don’t know if it’s possible to change buffer in the script.
Example: I wan to input a float ‘bufferedJump’ and it will test if it’s in the buffer passes the requirements, but I also want to change bufferedJump to -1. But it dose not work.
So this is what I need to know: Can this be done with a function and is there a better way to achieve this?
public void FixedUpdate()
{
if (CheckBufferedInput(inputJumpBuffered, inputBufferLength) /*& grounded*/)
{
//Player Jumps
}
if (inputJumpBuffered <= inputBufferLength && inputJumpBuffered != -1 )
{
inputJumpBuffered += Time.deltaTime;
}
}
bool CheckBufferedInput(float buffer, float bufferLength)
{
if (buffer <= bufferLength && buffer != -1)
{
return true;
}
else
{
return false;
}
buffer = -1; // <--- This no good
}
public void OnJump(InputAction.CallbackContext context)
{
if (context.started)
{
inputJumpBuffered = 0;
}
}
You can do this but you need to use the ref keyword.
The reason is that float variables are value types, so the local buffer argument is a fresh copy and when you change it, it does not change inputJumpBuffered
Look up using the ref keyword. You would use it in the function declaration AND you must use it at the call site to sort of confirm that’s what you mean.
void MyFunc( ref int x)
{
x++;
}
and to call it
MyFunc( ref myIntegerVariable);
Line 3 above will actually increment myIntegerVariable
As long as that variable is declared as ref in the function header, it MUST be passed in as ref, and when you change it, you are really changing the original variable. That can’t be changed dynamically without extra code deciding to copy it or whatever.