I’m trying to use a new Input System for local multiplayer.
If the script is on the same GameObject as PlayerInput, I can easily access methods OnJump, OnPickup like this:
private void OnJump(InputValue value)
{
jump = value.isPressed;
}
How can I access these methods in the child component?
I want to use OnPickup method:
private void OnPickup(InputValue value)
{
pickedUp = value.isPressed;
}
Best practice is to ALWAYS drag a reference of the child script into a public variable of the correct type.
If you want to live more dangerously, you can use this API:
BUT! It can fail if: you have more than 1 script instance in the children, there is 0 script instances in the children, etc.
So always best to directly drag a reference into the script that needs it. That is The Unity Way™.
You could change that dropdown on your PlayerInput from “Send Messages” to “Broadcast Messages”. That will also send messages to child objects.
You could also look into the “Send Unity Events” mode. If you select that, you’ll get a list of events underneath that dropdown and you can assign them specifically to call specific functions on specific components just like you can do for UI buttons.
1 Like
@Kurt-Dekker I was trying with reference but I have no idea how to do that.
@PraetorBlue “Broadcast Messages” works, but there is a lot of children GameObjects, I assume there could be a performance issue. I don’t know how “Send Unity Events” works but I will try to google it. Thank you for the direction.
You make a public variable of the type you need. In the case of what you’re doing I’m not 100% sure it applies now that Praetor chimed in, but it is basically the “drag this GameObject with this script into this slot” mechanism that 99.99% of every unity tutorial ever made uses.
yes, like I did for PickableHolder. The problem is I don’t know how to write code that would expose OnJump, OnPickup…
I created Event callbacks as PraetorBlue suggested.
I have two problems I don’t understand.
Code runs 3 times, and I would a lot of questions about this without answers.
I fix it with the if.
The second problem is the counter. In console counter updates normally but in the inspector, it stays at 0.
I don’t know why?
public int counter = 0;
public void OnPickup(InputAction.CallbackContext context)
{
if(context.performed && gameObject.scene.IsValid()) {
counter++;
print("Picked");
}
}