Unity 3D,如何生成 objects,并修改它们的值?

Unity 3D, how to spawn objects, and modify their values?

我尝试制作一个简单的 3D 轨道射击游戏,目前我还在研究如何为我的飞船生成子弹。

我希望当我着火时,子弹会生成并被射击。 我创建了一个空的游戏对象作为我的船的 child 并在上面放了一个脚本。

问题是我目前卡住了,我不知道如何完成它。 所以我寻求帮助,我错过了什么,我做错了什么?

这是我想出的脚本:

public Rigidbody rb;

private bool isMoving = false;
private bool isFirePressed = false;


void Start()
{
    rb = GetComponent<Rigidbody>();
    rb.useGravity = false;
}

void Update()
{
    isFirePressed = Input.GetButtonDown("Fire1");
}

void FixedUpdate()
{
    if (Input.GetButtonDown("Fire1"))
    {
        // the cube is going to move upwards in 10 units per second
        rb.velocity = new Vector3(0, 0, 100);
        isMoving = true;
        Debug.Log("fire");
    }
}

首先我猜你想使用你的变量 isFirePressed.

那么如果那是一个预制件,我猜你更想 Instantiate 一个新的子弹:

if (isFirePressed)
{
    var newBullet = Instantiate (rb, transform);
    // the cube is going to move upwards in 10 units per second
    newBullet.velocity = new Vector3(0, 0, 100);
    newBullet.useGravity = false;
    isMoving = true;
    Debug.Log("fire");
}

您更改了预制件上的速度,但不起作用。


另外请注意,velocity 在世界-Space 坐标中。所以目前无论你的飞机朝向哪里,你都在世界Z方向拍摄。

我宁愿使用例如

newBullet.velocity = transform.forward * 100;

朝 BulletEmitter 朝向的方向射击。