我试图在 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 () {
}
}
任何帮助是极大的赞赏!