通过脚本

时间:2016-01-03 01:06:43

标签: c# unity3d

此代码创建随机多维数据集和球体。我想在下面的代码中添加名为Destroy的脚本。我已在此脚本中添加了新材料,但我无法添加Destroy

代码:

public class RandomSpawn : MonoBehaviour 
{
    float toplam = 0;
    int a = 1;

    // Use this for initialization
    void Start () { }

    void Update()
    {
        toplam += Time.deltaTime;

        if (toplam < 1) return; 

        int x = Random.Range (-8, 9);
        int z = Random.Range (-4, 5);

        if (a == 1) 
        {
            GameObject cube = GameObject.CreatePrimitive (PrimitiveType.Cube);

            cube.AddComponent<Rigidbody> ();
            cube.transform.position = new Vector3 (x, 0.5f, z);
            MeshRenderer mr = cube.GetComponent<MeshRenderer>();

            int b = Random.Range (1, 5);

            if (b == 1) 
                mr.material = Resources.Load("cubeBlue", typeof(Material)) as Material;        
            else if (b == 2)
                mr.material = Resources.Load("cubeGreen", typeof(Material)) as Material;        
            else if (b == 3)
                mr.material = Resources.Load("cubeRed", typeof(Material)) as Material;
            else if (b == 4)
                mr.material = Resources.Load("cubeYellow", typeof(Material)) as Material;

            a = 0;
        } 
        else if(a == 0) 
        {
            GameObject sphere = GameObject.CreatePrimitive (PrimitiveType.Sphere);
            sphere.AddComponent<Rigidbody> ();
            sphere.transform.position = new Vector3 (x, 0.5f, z);
            MeshRenderer mr = sphere.GetComponent<MeshRenderer>();

            int b = Random.Range (1, 5);

            if (b == 1) 
                mr.material = Resources.Load("sphereBlue", typeof(Material)) as Material;
            else if (b == 2)
                mr.material = Resources.Load("sphereGreen", typeof(Material)) as Material;
            else if (b == 3)
                mr.material = Resources.Load("sphereRed", typeof(Material)) as Material;
            else if (b == 4)
                mr.material = Resources.Load("sphereYellow", typeof(Material)) as Material;  
            a = 1;
        }
        toplam -= 1f;  
    }
}

1 个答案:

答案 0 :(得分:0)

您需要调用函数AddComponent http://docs.unity3d.com/ScriptReference/GameObject.AddComponent.html

这就是你要找的东西。您可以像这样使用它:

// gameObject is created cube or sphere
Destroy myDestroyScript = gameObject.AddComponent<Destroy>();