0

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

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

实例化我的粒子类的多个实例(每个实例都包含一个单一的球体游戏对象)的正确方法是什么?

粒子类:

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
    }
}

自定义粒子系统类:

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 () {

    }
}

任何帮助是极大的赞赏!

4

1 回答 1

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

gameObject已定义,MonoBehaviour因此您应该已经可以访问它。

于 2014-10-06T17:55:12.807 回答