【发布时间】:2019-01-13 16:41:32
【问题描述】:
我试图让用户选择将当前游戏对象(立方体)更改为新形状(球体),但是,我不知道如何携带我为立方体到球体。
我已经设法销毁旧的立方体并将其替换为球体,但该球体似乎没有任何用于立方体的按键控件。我有一个想法,将新游戏对象的方法设置为我用于立方体的方法(即 newSphere.transform.rotation() = this.transform.rotation();),但它似乎不起作用。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class cubeControls : MonoBehaviour
{
// Constants for object rotation
public float moveSpeed = 80.0F;
public float turnSpeed = 100.0F;
// Initial scale of the original cube
public static Vector3 initscale = Vector3.one;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
/* Changing the position of the object
*
*/
// Moving the object right
if (Input.GetKey(KeyCode.D))
{
transform.Translate(Vector3.right * moveSpeed * Time.deltaTime);
}
// Moving the object left
if (Input.GetKey(KeyCode.A))
{
transform.Translate(Vector3.left * moveSpeed * Time.deltaTime);
}
/* Changing the rotation of the object
*
*/
// Rotating the cube to the right
if (Input.GetKey(KeyCode.RightArrow))
{
transform.Rotate(Vector3.up, turnSpeed * Time.deltaTime);
}
// Rotating the cube to the left
if (Input.GetKey(KeyCode.LeftArrow))
{
transform.Rotate(Vector3.down, turnSpeed * Time.deltaTime);
}
// Saving the current rendered material
Renderer rend = GetComponent<Renderer>();
/* Changing the scale of the object
*
*/
// Double the size of the cube
if (Input.GetKeyDown(KeyCode.Alpha2))
{
transform.localScale += new Vector3(2F, 2F, 2F);
}
/* Changing the color via key presses
*
*/
if (Input.GetKeyDown(KeyCode.R))
{
rend.material.SetColor("_Color", Color.red);
}
// Changing to sphere
if (Input.GetKeyDown(KeyCode.X))
{
GameObject newSphere = GameObject.CreatePrimitive(PrimitiveType.Sphere);
Destroy(this.gameObject);
}
}
}
【问题讨论】:
-
在调用destroy之前,
newSphere.AddComponent<cubeControls>() -
@SanSolo 哇哦!这比我想象的要简单得多,你知道我在哪里可以读到更多吗?我想确保我理解它为什么起作用:)
-
搜索如何在运行时向游戏对象添加脚本。本质上,脚本也是一个组件。所以添加/删除就像添加/删除任何组件一样
标签: c# visual-studio unity3d transform gameobject