Gun Class with Array List of Projectiles

I have a class named Gun and I want to have an Array List of projectiles from a Projectile class.

private List<Projectile> projectiles;

private void addProjectile()
{
	Projectile current = new Projectile();
	projectiles.Add(current);
}

While the game is executing I get an error saying “You are trying to create a MonoBehaviour using the ‘new’ keyword. This is not allowed.”

The projectile class has all the information I need plus it points to a mesh of a bullet.

How do I fix this problem?

Use the following instead:

GameObject proj = Instantiate( <ProjectileGameObject> ) as GameObject; projectiles.Add( proj.GetComponent<Projectile>() );

Replace <ProjectileGameObject> with a GameObject, usually a prefab of some sort.

The problem is that the class Projectile apperatnly inherits from MonoBehaviour, MonoBehaviour is needed to provide the unity functions update, awake, onMouseOpen and is needed to be able to attach a script on a gameObject in the inspector.

You have two solutions:

  1. You remove inheriting from MonoBehaviour in the Projectile class. This only works if Projectile don´t manipulate the world on anyway or use don´t use any GameObject functions.
  2. You add the class Projectile to the GameObject in the inspector then you use the code
    “projectileClass = gameObject.GetComponent(“Projectile”)” in the gun class Start() function.