简体   繁体   English

如何统一移动游戏预制件

[英]How to move a Game prefab in unity

Below is my code but I don't know why when the _lazerPrefab spawns it doesn't move, even though _lazerSpeed != 0 .下面是我的代码,但我不知道为什么当_lazerPrefab生成时它不会移动,即使_lazerSpeed != 0也是如此。 I dont't know where the problem is.我不知道问题出在哪里。

if (Input.GetKeyDown(KeyCode.Space))
{
    Instantiate(_lazerPrefab, transform.position, Quaternion.identity);
    _lazerPrefab.transform.Translate(Vector3.up * _lazerSpeed * Time.deltaTime);
}

You cannot move the prefab itself, as prefabs are like "blueprints" that are used to construct real object instances, hence the name.您不能移动预制件本身,因为预制件就像用于构建真实 object 实例的“蓝图”,因此得名。 You can indeed move those instances.您确实可以移动这些实例。 Instantiate() will return the reference to the newly created copy/instance! Instantiate() 将返回对新创建的副本/实例的引用!

if (Input.GetKeyDown(KeyCode.Space))
{
    GameObject new_lazer = Instantiate(_lazerPrefab, transform.position, Quaternion.identity);
    new_lazer.transform.Translate(Vector3.up * _lazerSpeed * Time.deltaTime);
}

But this code will always spawn a new instance when you press Space.但是,当您按空格键时,此代码将始终生成一个新实例。 And once you spawned a 2nd, you will no longer move the first as the Translate call for the first instance is not done anymore.一旦你产生了第二个,你将不再移动第一个,因为第一个实例的Translate调用不再完成。

So you need to adapt your logic.所以你需要调整你的逻辑。 Either put a "move/accelerate forward" script on the lazers, or keep the references returned from Instantiate() in a list and maintain them and their lifetime.要么在 lazers 上放置“移动/加速前进”脚本,要么将Instantiate()返回的引用保存在列表中并维护它们及其生命周期。

You are only moving the _lazerprefab when Input.GetKeyDown(KeyCode.Space) is true.仅当Input.GetKeyDown(KeyCode.Space)为真时,您才移动_lazerprefab

If you want to move the gameObject more than once after you press space you would need to add the move code into the gameObjects Update() Method itself.如果您想在按下空格键后多次移动gameObject ,则需要将移动代码添加到游戏对象的Update()方法本身中。

You would need to attach this script to the _lazerprefab GameObject.您需要将此脚本附加到_lazerprefab游戏对象。

Example Script:示例脚本:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MoveObstacles : MonoBehaviour {
    [SerializeField]
    private float _lazerSpeed = 10f;

    private void FixedUpdate() {
        gameObject.transform.Translate(Vector3.up * _lazerSpeed * Time.deltaTime);
    }
}

We are now able to just call the Instantiate() Function and the instantiated GameObject will move automatically each frame.我们现在可以调用Instantiate() Function 并且实例化GameObject对象将在每一帧自动移动。

Example Move Call:移动调用示例:

if (Input.GetKeyDown(KeyCode.Space)) {
    Instantiate(_lazerPrefab, transform.position, Quaternion.identity);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM