How to instantiate a game object every time when space key is pressed
I want to instantiate a game object every time when the space key is pressed. Please help me with some solution below is my code-
public class arrow : MonoBehaviour { public Rigidbody2D rb; public float speed; public GameObject arow; // Use this for initialization void Start () {
}
// Update is called once per frame
void Update () {
float x = Input.GetAxis ("Horizontal");
if (x > 0) {
MoveRight ();
}
if (Input.GetKeyDown (KeyCode.Space)) {
Instantiate (arow);
}
}
void MoveRight(){
rb.velocity = new Vector2 (speed, 0);
}
void OnCollisionEnter2D(Collision2D col){
if (col.gameObject.tag == "ball") {
Destroy (gameObject);
}
}
Answer by Reaper93 · May 17, 2017 at 03:58 PM
For that you will need some boolean and set it to true whenever you press the button and set it to false whenever you release it for example:
private bool SpacePressed=false;
void Update
{
if (Input.GetKeyDown (KeyCode.Space)&& !SpacePressed)
{
Instantiate (arow);
SpacePressed=true;
}
else if (Input.GetKeyUp (KeyCode.Space))
{
SpacePressed=false;
}
}
@prrashanthh FIrst of all you will have to Store a reference in your script right after you instantiate that object like so:
GameObject myItem=(GameObject)Instantiate(Item, transform.position, transform.rotation);
Then you will have to AddForce to its Rigidbody component or simply Translate a Transform component in desired direction.
lAddForce
lTranslate
Hope That is clear enough)
Answer by prrashanthh · May 18, 2017 at 10:52 AM
First of all thanks for your reply. Actually, I want the game object to be instantiated at starting position and it should move in a straight way. It will be a great help if you can help me with the code. Thanks.