C# 如何向Unity3D中的实例化游戏对象添加行为脚本?

C# 如何向Unity3D中的实例化游戏对象添加行为脚本?,c#,unity3d,C#,Unity3d,我正在做一个游戏,你可以用鼠标左键实例化立方体。现在我想用箭头键旋转这些实例化的立方体。我想知道,如何将下面的代码与我的实例化多维数据集连接起来! (顺便说一句,我实例化的多维数据集保存在列表中。) 我的旋转代码: if (Input.GetKey (KeyCode.LeftArrow)) { transform.Rotate(0, 0, rotationAngle * Time.deltaTime, Space.World); } if (In

我正在做一个游戏,你可以用鼠标左键实例化立方体。现在我想用箭头键旋转这些实例化的立方体。我想知道,如何将下面的代码与我的实例化多维数据集连接起来! (顺便说一句,我实例化的多维数据集保存在列表中。)

我的旋转代码:

    if (Input.GetKey (KeyCode.LeftArrow))
    {
        transform.Rotate(0, 0, rotationAngle * Time.deltaTime, Space.World);
    }

    if (Input.GetKey (KeyCode.RightArrow))
    {
        transform.Rotate(0, 0, - rotationAngle * Time.deltaTime, Space.World);
    }

将该代码放在脚本中,并将其命名为RotateOnKeys,然后在实例化多维数据集的脚本中执行以下操作:

// This is the line of code that you're already using to spawn a cube:
GameObject cube = GameObject.Instantiate(cubePrefab) as GameObject;

// This is the line of code needed to attach a script:
cube.AddComponent<RotateOnKeys>();
public class SpinGameObject : MonoBehaviour
{
    void Update()
    {
        if (Input.GetKey (KeyCode.LeftArrow))
        {
            transform.Rotate(0, 0, rotationAngle * Time.deltaTime, Space.World);
        }

        if (Input.GetKey (KeyCode.RightArrow))
        {
            transform.Rotate(0, 0, - rotationAngle * Time.deltaTime, Space.World);
        }
    }
}
//这是您已经用来生成多维数据集的代码行:
GameObject cube=GameObject.实例化(cubePrefab)为GameObject;
//这是附加脚本所需的代码行:
AddComponent();

好吧,您正在寻找一种叫做预制的东西prefable是预先制作的对象,您可以向其中添加脚本等,然后您可以实例化此prefable。A

编辑
或者你可以用@Jayson Ash的方式来做。

有几种方法可以做,就像大多数与编程相关的事情一样

首先,你要把它放在一个单一的行为中。具体来说,您可能希望它出现在Update()循环中。大概是这样的:

// This is the line of code that you're already using to spawn a cube:
GameObject cube = GameObject.Instantiate(cubePrefab) as GameObject;

// This is the line of code needed to attach a script:
cube.AddComponent<RotateOnKeys>();
public class SpinGameObject : MonoBehaviour
{
    void Update()
    {
        if (Input.GetKey (KeyCode.LeftArrow))
        {
            transform.Rotate(0, 0, rotationAngle * Time.deltaTime, Space.World);
        }

        if (Input.GetKey (KeyCode.RightArrow))
        {
            transform.Rotate(0, 0, - rotationAngle * Time.deltaTime, Space.World);
        }
    }
}
如果您想在所有的多维数据集上都使用它,您可以将它直接附加到正在实例化的预置中

否则,如果您想选择将其应用于哪些多维数据集,您可以获取包含多维数据集的实例化游戏对象,然后调用以下函数:

void AttachScriptToGameObject(GameObject go)
{
    go.AddComponent<SpinGameObject>();
}
void AttachScriptToGameObject(游戏对象go)
{
go.AddComponent();
}
希望有帮助

编辑:
很多人回应,所有这些工作:)

不完全是我所期望的,但它起了作用:)谢谢!