Let's say we want to execute especific code for a certain platform, usually this problem arises when we are targeting multiple platforms and some features/characteristics are different.
Often we want to do this with the input between PC and Mobile, so if we have this on PC.
void Update () {
if (Input.GetKey(KeyCode.D)) { //Move right
rigidbody2D.velocity = new Vector2(speed, 0.0f);
}
else if (Input.GetKey(KeyCode.A)) { //Move left
rigidbody2D.velocity = new Vector2(-speed, 0.0f);
}
else { //Does not move
rigidbody2D.velocity = new Vector2(0.0f, 0.0f);
}
}
On mobile this won't work.
We could add the mobile input code next to it but everything will be executed, so here's where we use Platform #define directives.
void Update () {
#if UNITY_STANDALONE || UNITY_WEBGL || UNITY_EDITOR //PC Input
if (Input.GetKey(KeyCode.D)) { //Move right
rigidbody2D.velocity = new Vector2(speed, 0.0f);
}
else if (Input.GetKey(KeyCode.A)) { //Move left
rigidbody2D.velocity = new Vector2(-speed, 0.0f);
}
else { //Does not move
rigidbody2D.velocity = new Vector2(0.0f, 0.0f);
}
#elif UNITY_ANDROID || UNITY_IOS //Mobile Input
if (Input.GetTouch(0).position.x > Screen.width / 2.0f) { //Move right
rigidbody2D.velocity = new Vector2(speed, 0.0f);
}
else if (Input.GetTouch(0).position.x < Screen.width / 2.0f) { //Move left
rigidbody2D.velocity = new Vector2(-speed, 0.0f);
}
else { //Does not move
rigidbody2D.velocity = new Vector2(0.0f, 0.0f);
}
#endif
}
In this we define certain code regions that will only be compiled if the current selected platform matches the property inside the #if / #elif statements.
For more info on which property to use check the table.
No comments:
Post a Comment