在 C# 和 Unity 中使用 input.getkeydown(KeyCode.Space) 创建游戏对象的副本时遇



编码有点新,所以帮助将不胜感激。我正在尝试在统一中复制这个游戏对象"立方体",但我遇到了麻烦。我试图做的是复制立方体并让它一遍又一遍地堆叠在一起。

我知道如果我让它工作,它会在同一个位置上重复它,所以你只会在高层看到它重复。

using System.Collections;
using UnityEngine;
public class cube : MonoBehaviour
{
public GameObject cube1;
public void update()
if(input.getKeyDown(KeyCode.Space))
{ 
instantiate cube1; 
}
}

我假设你知道立方体的高度,你正在使用。在 Unity 中,默认高度为 1.0f(对于原始立方体(。

顺便说一句,如果你的代码是伪代码,那么它就是okey,但如果不是,在编写这样的脚本之前你需要更多的培训,即使这种类型的脚本非常容易编写。 (PS:我用记事本++编写了这个脚本,希望它可以编译:/(

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
// We start classes with capital letters in c# its a convention :)
public class Cube : MonoBehaviour
{
// Same applies to public class fields & Properties
// Marking a MonoBehaviour field as public will allow you to directly assign values to it
// inside the editor
public GameObject OriginalCube;
// Same can be achieved with private fields using the serializefield attribute
[SerializeField]
private float cubeHeight = 1.0f;
// In case you would like to store the duplicated cubes
public List<GameObject> Cubes = new List<GameObject>();
private void Awake()
{
// Adding the first cube to the list, i assume your cube is already in the scene
Cubes.Add(OriginalCube);
}
private void Update()
{
if(Input.GetKeyDown(KeyCode.Space))
{ 
// We instantiate a new cube and add it to the list
Cubes.Add(Instantiate(Cubes[Cubes.Count - 1]);
// We ask the previous cube position (the one we copied)
Vector3 previousCubePosition = Cubes[Cubes.Count - 2].transform.position;
// then we assign a new position to our cube raised by "1 unit" on the y axis which is the up axis in unity
Cubes[Cubes.Count - 1].transform.position = 
new Vector3(previousCubePosition.x, previousCubePosition.y + cubeHeight, previousCubePosition.z);
}
}
}

实现目标的一种方法是向新实例化的对象的 y 位置添加一个常量。每次创建对象的新副本时,此常量量都会增加。

public GameObject cube1;
private int instantiateCounter = 0;
public float PULL_UP_AMOUNT = 30f;
public void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
instantiateCounter++;
GameObject newCube = Instantiate(cube1);
newCube.transform.position = new Vector3(cube1.transform.position.x, cube1.transform.position.y + instantiateCounter * PULL_UP_AMOUNT, cube1.transform.position.z);
}
}

我们正在谈论的恒定量是PULL_UP_AMOUNT.

请记住,您可以通过将方法的结果保存在新GameObject中来访问新副本的属性Instantiate就像我一样。

最新更新