0

Unity で C# スクリプトを使用して多数の「パーティクル」をインスタンス化しようとしています。対応するゲームオブジェクトの作成を含むパーティクル クラスを作成しました。各パーティクル インスタンス内のゲーム オブジェクトは球体です。新しいパーティクル (Particle p = new Particle(...)) をインスタンス化しようとすると、「new」キーワードを使用しないでくださいという Unity の警告が表示されます。

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

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

    }
}

どんな助けでも大歓迎です!

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 に答える