- Home /
Instantiating on Input
Right now when I hit play in Unity a cube Instantitates right away. I am trying to have the cube instantiate on Input,(when I press T) but I am having a lot of trouble. When I execute the code in the Update method or FixedUpdate method it just spawns a ton of cubes. My code is below in C#. As you can see I have the code executed in the Start method. Any help is appreciated. Thank you for your time.
using UnityEngine;
using System.Collections;
public class Creator : MonoBehaviour {
public GameObject thePrefab;
// Use this for initialization
void Start () {
if(Input.GetKeyDown(KeyCode.T));
GameObject instance = Instantiate(thePrefab, transform.position, transform.rotation) as GameObject;
}
}
Answer by Berenger · Jun 11, 2012 at 07:21 PM
Start is called once per instance of the script (so by object it's attached to) before any Update is called.
Input.GetXXX functions lookup the state of the input requested and return true if it is correct => you're if will return true at the exact frame you press T. That's why it needs to be tested in Update, not Start. Then, it should work and instantiate only once (per instance of that script mind you, but the name Generator suggest that there is only one).
Your answer
Follow this Question
Related Questions
Lightswitch help? 3 Answers
Distribute terrain in zones 3 Answers
Multiple Cars not working 1 Answer
Input loss. One out of every five or six mouse clicks or button presses don't register. 1 Answer