2016-03-03 151 views
1

這是我的一個多維數據集遊戲的代碼。其實我想要這樣的代碼運行如: 當我按「空間」一旦它必須生成一個立方體,目前它生成一個以上的一個時間按下「空間」按鈕多個立方體。其次,當我使用箭頭鍵時,它必須從當前站立的那個位置生成立方體,但是暫時它只是從中心生成立方體。腳本問題統一3D

using UnityEngine; 
using System.Collections; 

public class fire : MonoBehaviour { 

    void OnCollisionEnter(Collision collision) 
    { 
     if (collision.gameObject.name == "brick" || collision.gameObject.name == "a" || collision.gameObject.name == "b") 
     { 
      Destroy(collision.gameObject); 
     } 
    } 

    public float speed; 
    // Use this for initialization 
    void Start() { 

    } 

    // Update is called once per frame 
    void Update() { 

     transform.Translate(speed * Input.GetAxis("Horizontal") * Time.deltaTime, 0f, 0f); 

     if (Input.GetKey(KeyCode.Space)) 
     { 
      transform.Translate(speed * Vector3.up * Time.deltaTime);    
     } 
     Vector3 temp = transform.position; 
     if (Input.GetKey(KeyCode.Space)) 
     { 

      GameObject textObject = (GameObject)Instantiate(Resources.Load("ball")); 
     } 

    } 

} 
+0

你可以***不使用「unityscript」。它被棄用,不起作用,並且正在從Unity中刪除。幸運的是,c#實際上對於初學者來說更容易。請享用。 – Fattie

+0

[Unity3d - Input.GetKey可能重複不止一次返回true](http://stackoverflow.com/questions/30727530/unity3d-input-getkey-returns-true-more-than-once) – Fattie

回答

2
  1. 嘗試使用Input.GetKeyUp或GetKeyDown,而不是信息getKey。

  2. 您可以調用GameObject.Instantiate並在想要實例化對象的位置。

+0

穆罕默德請考慮一下對象池。這對性能也有好處。 –

0

http://docs.unity3d.com/ScriptReference/Input.GetKey.html「當用戶按住名稱標識的按鍵時返回true,認爲自動點火。所以如果你按下鍵的1/10秒,更新被稱爲每秒60次,你會得到六個立方體。

通常情況下,您希望將對象創建綁定到keydown或keyup事件,因爲只會觸發一次。

1

如何使用Input.GetKeyUp?

using UnityEngine; 
using System.Collections; 

public class ExampleClass : MonoBehaviour { 
    void Update() { 
     if (Input.GetKeyUp("space")) 
      print("space key was released"); 

    } 
}