# Can I trigger input/controls via code?

I have the 3rd person controller in my game, which moves with the WASD keys. But since I am developing for a mobile release, I want touch controls.

I have already the touch control-script in a new script-file, but attached to the same 3rd person controller-prefab.

When I swipe right for instance, I want Unity to trigger the D-key etc.

How can I do that?

...
if (Mathf.Abs(delta.x) > Mathf.Abs(delta.y))
{
if (delta.x > 0)
//trigger D?
else if (delta.x < 0)
//trigger A?
}
...


First make a function that triggers the real action:

void moveLeft() { .. }


Then determine when to call it based on the platform:

Desktop: if(A key down) { moveLeft(); }
Mobile: if(swiping left) { moveLeft(); }

Another solution is to do the opposite:

Create some kind of interface/class that reads input:

// (this is a general solution not specific to Unity)
interface ICharacterController
{
bool shouldMoveLeft();
bool shouldJump();
}


Then, in your character class, have a method like setController(ICharacterController c). In your character's logic code, call the aforementioned methods to determine what action to take.

Finally, implement the given interface and assign it separate for desktop and mobile.

Looking quickly at the Unity docs, it seems like using sendMessage() might be a good alternative to keeping references, if you want to reduce dependencies between your classes.

• So you guess using sendMessage then? Because the movement-method and the touch-method are in two different scripts – IMX Dec 16 '13 at 13:24
• @Anko Thanks for the formatting. I've been doing the LD48 all weekend and I'm pretty tired ~_~ – tacospice Dec 16 '13 at 15:45
• @IMX I haven't touched Unity in quite a while, this is just a general solution, but sendMessage() might do the trick. I'd keep a reference somewhere to the object being controlled (or to the input). I'll add some more to the answer. – tacospice Dec 16 '13 at 15:47

Your best choice, whilst keeping code simple, is to use Platform Specific Compilation. This will allow you to have one component that houses player input for multiple platforms.

For example:

public class PlayerController : MonoBehaviour {
void Update () {

#if UNITY_STANDALONE
if (Input.GetKey(KeyCode.A))
moveLeft();
// Etc.
#endif

#if UNITY_IPHONE
// Touch logic for iPhone here
#endif

#if UNITY_ANDROID
// Touch logic for Android here
#endif
}
}


The compiler will then cherry pick which block to use based on your build target and will discard any non applicable clauses.