Unity 创建对象

CreatePrimitive 方式创建对象

PrimitiveType {
    Sphere,//球体
    Capsule,//胶囊体
    Cylinder,//圆柱体
    Cube,//方块
    Plane,//平面
    Quad,//四边形
}

C#:

void OnGUI () {

        if (GUILayout.Button("创建立方体",GUILayout.Height(50))) {
            var obj = GameObject.CreatePrimitive (PrimitiveType.Cube);
            obj.AddComponent<Rigidbody> ();
            obj.name = "MyCube";
            obj.transform.position = new Vector3 (0, 10, 0);

            Renderer renderer = obj.GetComponent<Renderer> ();
            renderer.material.color = Color.red;
        }
        if (GUILayout.Button ("创建球体", GUILayout.Height (50))) {
            var obj = GameObject.CreatePrimitive (PrimitiveType.Sphere);
            obj.AddComponent<Rigidbody> ();
            obj.name = "MySphere";
            obj.transform.position = new Vector3 (0, 10, 0);

            Renderer renderer = obj.GetComponent<Renderer> ();
            renderer.material.color = Color.green;
        }
    }

Instantiate 方式创建对象 (需要引入 prefab )

通过 prefab 预制体 来创建对象。
C# :

public Rigidbody projectile;

void Update() {
    if (Input.GetButtonDown("Fire1")) {
        Rigidbody clone;
        clone = Instantiate(projectile, transform.position, transform.rotation);
        clone.velocity = transform.TransformDirection(Vector3.forward * 10);
    }
}

PS:点击左键,向 Z轴 发射预制体。

Instantiate 方式创建对象 (无需引入 prefab )

首先,在 Assets 文件夹下创建一个名为 Resources 文件夹,然后将 prefab 预制体 放到该目录下就可以使用 Resources.Load() 方式加载。

简单的来说就是:
C#:

void Update() {
    if (Input.GetButtonDown("Fire1")) {
        GameObject pref = Resources.Load ("3Sphere") as GameObject;
        Instantiate (pref);
    }
}

套用上面的效果就是:
C#:

void Update() {
    if (Input.GetButtonDown("Fire1")) {
        GameObject pref = Resources.Load ("3Sphere") as GameObject;

        GameObject clone;
        clone = Instantiate(pref, transform.position, transform.rotation);

        Rigidbody rigidbody = clone.GetComponent<Rigidbody> ();
        rigidbody.velocity = transform.TransformDirection(Vector3.forward * 10);
    }
}

PS:3Sphere 这个预制体 有 Rigidbody 这个组件的。

关于路径方式加载,还有一种方式:
首先引入模块:

using UnityEditor;

然后代码:
C#:

void Update() {
    if (Input.GetButtonDown("Fire1")) {
        GameObject pref = AssetDatabase.LoadAssetAtPath("Assets/Resources/3Sphere.prefab", typeof(GameObject)) as GameObject;
            
        //剩余的同上。。。。。
    }
}