脚本问题 Unity 3D
本文关键字:3D Unity 问题 脚本 | 更新日期: 2023-09-27 18:37:18
这是我的立方体游戏代码。实际上我希望这段代码像这样运行:当我按"空间"一次它必须生成一个立方体时,目前它一次按下"空间"按钮生成多个立方体。其次,当我使用箭头键时,它必须从我当前站立的位置生成立方体,但暂时它只是从中心生成立方体。
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"));
}
}
}
-
尝试使用 Input.GetKeyUp 或 GetKeyDown 而不是 GetKey。
-
您可以使用要实例化对象的位置调用 GameObject.Instantiate。
使用 Input.GetKeyUp ???
怎么样?using UnityEngine;
using System.Collections;
public class ExampleClass : MonoBehaviour {
void Update() {
if (Input.GetKeyUp("space"))
print("space key was released");
}
}
from http://docs.unity3d.com/ScriptReference/Input.GetKey.html "在用户按住由名称标识的键时返回 true。想想自动开火。 因此,如果您按下 1/10 秒的键并且每秒调用更新 60 次,您将获得大约六个立方体。
通常,您希望将对象创建与键合或键控事件相关联,因为这只会触发一次。
您可能希望使用 Input.GetKeyDown("space") 来实例化游戏对象一次。这是因为它只会在您按下它的帧期间返回 true。您正在使用的 Input.GetKey 将在您仍在按下按钮时返回 true。所以你可以做这样的事情:
void Update()
{
if(Input.GetKeyDown("space")
{
GameObject textObject = (GameObject)Instantiate(Resources.Load("ball"));
}
}