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?