如何实例化包含GameObject的对象类?

时间:2014-10-06 17:51:45

标签: c# unity3d instantiation particles gameobject

我试图实例化大量的"粒子"在Unity中使用C#脚本。我创建了一个包含相应GameObject创建的粒子类。每个粒子实例中的GameObject是一个球体。当试图实例化一个新的粒子(粒子p =新粒子(...))时,我得到一个Unity警告,即“' new'不应使用关键字。

"您正尝试使用' new'创建MonoBehaviour。关键词。这是不允许的。 MonoBehaviours只能使用AddComponent()添加。或者,您的脚本可以继承ScriptableObject或根本不继承基类 UnityEngine.MonoBehaviour:.ctor()"

实例化粒子类的多个实例(每个实例包含一个奇异的球体GameObject)的正确方法是什么?

粒子类:

public class Particle : MonoBehaviour {

    Vector3 position = new Vector3();
    Vector3 velocity = new Vector3();
    Vector3 force = new Vector3();
    Vector3 gravity = new Vector3(0,-9.81f,0);
    int age;
    int maxAge;
    int mass;
    GameObject gameObj = new GameObject();

    public Particle(Vector3 position, Vector3 velocity)
    {
        this.position = position;
        this.velocity = velocity;
        this.force = Vector3.zero;
        age = 0;
        maxAge = 250;
    }
    // Use this for initialization
    void Start () {
        gameObj = GameObject.CreatePrimitive (PrimitiveType.Sphere);

        //gameObj.transform.localScale (1, 1, 1);
        gameObj.transform.position = position;
    }

    // FixedUopdate is called at a fixed rate - 50fps
    void FixedUpdate () {

    }

    // Update is called once per frame
    public void Update () {
        velocity += gravity * Time.deltaTime;
        //transform.position += velocity * Time.deltaTime;
        gameObj.transform.position = velocity * Time.deltaTime;

        Debug.Log ("Velocity: " + velocity);
        //this.position = this.position + (this.velocity * Time.deltaTime);
        //gameObj.transform.position
    }
}

CustomParticleSystem类:

public class CustomParticleSystem : MonoBehaviour {

    Vector3 initPos = new Vector3(0, 15, 0);
    Vector3 initVel = Vector3.zero;
    private Particle p;
    ArrayList Particles = new ArrayList();

    // Use this for initialization
    void Start () {
        Particle p = new Particle (initPos, initVel);
        Particles.Add (p);
    }

    // Update is called once per frame
    void Update () {

    }
}

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:1)

除了gameObj

意外输入错误声明之外,您的代码看起来很好

GameObject gameObj = new GameObject();课程中的GameObject gameObj = null;更改为Particle

该错误明确提到您不能做您所做的事情,并在Start()中设置它就像它提到的那样。

编辑:查看Particle,它会继承MonoBehaviour。您需要gameObject使用gameObject.AddComponent<Particle>();

为您创建实例

http://docs.unity3d.com/ScriptReference/GameObject.AddComponent.html

gameObjectMonoBehaviour上定义,因此您应该可以访问它。

相关问题