I'm trying to implement a "Shoot" MonoBehaviour. I want it to do something very simple, it should take a Prefab as "Input" (storing it in a "projectile" public variable for the time being), and then simply Instantiate it and add a Forward force to it's RigidBody (relative to the object it is attached to, for example, a Tank).
However, I don't want my game to crash if I accidentally insert a Prefab that doesn't have a RigidBody. (In fact, it would be great if it didn't even allow me to add Prefabs without RigidBodies as projectiles).
I've tried using the "RequireComponent" attribute, but it looks like it only works for classes. Is there any way to do this without having to check if the Projectile has a RigidBody each time I want to shoot it?
I tried the Code Below, but it gives me an error saying I can't Instantiate a RigidBody as a GameObject. Which is understandable, but I'm running out of ideas here.
public class Shoot : MonoBehaviour
{
public Rigidbody projectile;
public float firePower = 5f;
public void Fire()
{
GameObject projectileInstance = Instantiate(projectile) as GameObject;
//maybe add some particles/smoke effect
projectile.GetComponent<Rigidbody>().AddForce(firePower * transform.forward);
}
}