2016-03-03 147 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"); 

    } 
}