- Home /
Cannot use "new" keyword on class inheriting from MonoBehaviour
I have a class called ShootBulletPlayer.cs and in it I have a Gun class (which doesn't inherit from MonoBehaviour), and two types of guns that inherit from it: StandardGun and PushBackGun.
public class Gun {
public string prefabLocation;
public GameObject gun;
public Bullet bullet;
public Gun()
{
}
}
public class StandardGun : Gun
{
public StandardGun()
{
prefabLocation = "Prefabs/RayGun";
bullet = new Bullet.StandardBullet();
}
}
public class PushBackGun : Gun
{
public PushBackGun()
{
prefabLocation = "Prefabs/RayGunV2";
bullet = new Bullet.PushBackBullet();
}
}
As you can see, each gun has its own special bullet it's referencing upon construction which has its own unique properties. I get the following error when I create each bullet in each specific guns constructor: "You are trying to create a MonoBehaviour using the 'new' keyword. MonoBehaviours can only use added using AddComponent()" I know this is because my Bullet class inherits from MonoBehavior and therefore I should not use the "new" keyword to create a new instance of each bullet, but I don't know any other way to assign a new bullet to each gun upon its construction. Here is my bullet code which is located in a class called Bullet.cs:
public class Bullet : MonoBehaviour{
public GameObject bulletObject;
private float pushBackAmount;
public float shotSpeed;
public string prefabLocation;
public float spawnDistanceFromGun;
public class StandardBullet : Bullet
{
public StandardBullet()
{
pushBackAmount = 2f;
shotSpeed = 100f;
prefabLocation = "Prefabs/StandardBullet";
spawnDistanceFromGun = 2f;
}
}
public class PushBackBullet : Bullet
{
public PushBackBullet()
{
pushBackAmount = 5f;
shotSpeed = 100f;
prefabLocation = "Prefabs/PushBackBullet";
spawnDistanceFromGun = 2f;
}
}
} As you can see, each bullet has its own properties like "pushBackAmount" and "shotSpeed." How can I create a new bullet in each gun's constructor so that the variables like "pushBackAmount" and "shotSpeed" will be correctly passed?
Answer by gjf · Mar 01, 2015 at 08:55 AM
if you're inheriting from MonoBehaviour, your script is a component so add it as one...
and put the inherited classes in their own script.
I understand that but I don't know the correct coding syntax. I'm trying but I can't get it to compile. That is why I posted my code and the dependencies so that someone could hopefully help provide me the correct syntax to create a new bullet in the gun constructor
Answer by siaran · Mar 01, 2015 at 08:51 PM
Don't create a new bullet in the gun constructor - that doesn't even make sense.
Create prefabs for all your types of bullets and set their values, then drag the correct one into the bulletObject field on your Gun script in the editor for each type of gun.