unity用代码创建cube并控制长宽
时间: 2024-05-09 10:20:18 浏览: 87
下面是一个示例代码,用于在Unity中创建一个Cube,并控制其长宽:
```csharp
using UnityEngine;
public class CubeController : MonoBehaviour
{
public float width = 1f;
public float height = 1f;
public float depth = 1f;
// Start is called before the first frame update
void Start()
{
// 创建一个Cube
GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
// 设置Cube的大小
cube.transform.localScale = new Vector3(width, height, depth);
// 将Cube添加到当前对象的子对象中
cube.transform.parent = transform;
}
// Update is called once per frame
void Update()
{
// 在Update函数中可以控制Cube的长宽
if (Input.GetKey(KeyCode.UpArrow))
{
height += 0.1f;
transform.GetChild(0).localScale = new Vector3(width, height, depth);
}
if (Input.GetKey(KeyCode.DownArrow))
{
height -= 0.1f;
transform.GetChild(0).localScale = new Vector3(width, height, depth);
}
if (Input.GetKey(KeyCode.LeftArrow))
{
width -= 0.1f;
transform.GetChild(0).localScale = new Vector3(width, height, depth);
}
if (Input.GetKey(KeyCode.RightArrow))
{
width += 0.1f;
transform.GetChild(0).localScale = new Vector3(width, height, depth);
}
}
}
```
将以上代码添加到一个空对象上,运行游戏,就可以看到一个Cube,并且可以通过键盘控制其长宽。
阅读全文