How can I Require a public Variable (Prefab) to have a certain component (RigidBody) in UNITY?

unity get component of another gameobject
unity requirecomponent
unity get component of gameobject
unity rigidbody
unity gameobject
unity requirecomponent not working
unity instantiate
unity instantiate prefab

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);

The others here already gave you some examples on how you would do this at runtime, however I would recommend you add a [RequireComponent(typeof(RigidBody))] to your projectile class (if you have one).

What that does is every time you attach your component to a gameObject Unity will automatically add the required components as well without having a performance impact on your game on runtime. Just add this over the class declaration on your projectile script.

You do however need to manually assign your components via the Inspector or by GetComponent. But this makes sure that your object has the right components attached.

You need some sort of script on your projectiles for this to work tho. So if you do not have that you should use another option pointed out here.

The documentation can be found here if you are interested.

Controlling GameObjects using components - Unity, Prefabs � Creating Prefabs � Editing a Prefab in Prefab Mode void Start () { Rigidbody rb = GetComponent<Rigidbody>(); // Add a force to the Rigidbody. rb. Additionally, if you declare a public variable of a Component type in your script, you in the Scene hierarchy as long as you have some information to identify them. When making a public Prefab variable, the variable type can be a GameObject, or it can be any valid Component type (either a built-in Unity component or one of your own MonoBehaviour script). For GameObject type variables, you can assign any GameObject to the variable, and the Instantiate function returns a reference to the new GameObject instance.

You can do a check on the prefab to see if it has a Rigidbody component like so:

if (currentPrefab.GetComponent<Rigidbody>()){

    // Do something


The GameObject.GetComponent() method will return null if the type you enter as a parameter is not present.

Scripting API: RequireComponent, For some reason your suggested change could not be submitted. The RequireComponent attribute automatically adds required components as PlayerScript requires the GameObject to have a Rigidbody component [ RequireComponent(typeof(Rigidbody))] public class PlayerScript : MonoBehaviour { Rigidbody rb; This is useful to avoid setup errors. For example a script might require that a Rigidbody is always added to the same GameObject. Using RequireComponent this will be done automatically, thus you can never get the setup wrong. Note that RequireComponent only checks for missing dependencies during the moment the component is added to a GameObject.

You can add in the components that you want at runtime, for example:

    // First check if there is no rigidbody component on the object
    if (!currentPrefab.GetComponent<Rigidbody>()){
        // Add the Rigidbody component

        // You can also add a collider here if you want collisions
        var bc = currentPrefab.AddComponent<BoxCollider>();

        // And you'll have to calculate the new collider's bounds
        Renderer[] r = t.GetComponentsInChildren<Renderer>();
        for(var i=0; i<r.length; i++) {

C# setting instantiated prefab variables from another script., Presumably you have some script on your instantiated object? Maybe GetComponent<Thing>();; //set a member variable (must be PUBLIC) //maybe access one of the built in components (such as a rigid body if it has one)� How can I Require a public Variable (Prefab) to have a certain component (RigidBody) in UNITY? 1. How can I grab a reference of a game-object in a scene from a prefab. 0.

I believe you are already on the write track. You just have to fix your error by doing the following :

public Rigidbody projectile;
public float firePower = 5f;

public void Fire()
    if( projectile == null )
         Debug.LogError( "You forgot to provide a projectile prefab");
    Rigidbody projectileInstance = Instantiate(projectile) as Rigidbody;
    projectileInstance.AddForce(firePower * transform.forward);

However, with this method, you can't require the prefab to have multiple components. If you need this, then, go with the method provided by the other answers.

The variable has not been assigned (but it has), It has several prefabs assigned to it, and they work flawlessly. However, when I added a new prefab to the script and assigned it in the inspector, I get an error: public GameObject copper;; private GameCamera cam;; public int iB = 1; I didn' t know the 2nd component copy existed, so I didn't look go� Prefab variants are variations of a prefab that are saved as a separate prefab asset. They share their data with the original prefab asset but have a few overridden properties that differ from the original prefab. For example, you can create a variant of a character but with different colors.

Get public variable from other gameobject unity, We can have a public variable of type game object that we attach to another game object, Instantiate(prefab);} The scene is loading in my serialised object into a new Jan 06, 2015 � There are two components needed to play sounds in Unity, is the "local" GameObject that the script instance is attached to. rigidbody and� When I have a variable reference like var test : Transform from a script in a prefab is there something i need to drag onto the variable reference in the script component in the inspector? The asset click at the far right brings up an empty window. I broke a prefab and now the 'var test : transform' doesn't hook onto anything and at runtime I get :

[PDF] CMSC 425: Lecture 3 Introduction to Unity, Unity Basic Concepts: The fundamental structures that make up Unity are the Prefabs: A prefab is a template for grouping various assets under a single header . A rigid body component that specifies how the object moves physically in space mechanism for passing game objects through the public variables of a script. 4. Learn how Rigidbody objects should be moved. Rigidbodys in Unity have a lot of properties which are hidden from the inspector. An object doesn’t only have a position, but also a speed, an angular velocity, etc. If you change the position of an object by using a script, you are likely to create inconsistencies in these hidden variables.

Unity: Using RigidBody AddForce() method to move , Using RigidBody AddForce() method to move Game Object in Unity. can also use some built-in methods to enhnance movement effects of game objects. where prefab is created fireballXValue = gameObject.transform.position.x; First off, we still have to declare the Rigidbody2D variable, but instead of making it public� While earlier, we used to update any component's property using the Inspector view. Here, we will try to do that from within the script. First off, we still have to declare the Rigidbody2D variable, but instead of making it public, let's make it private instead. private RigidBody2D fireballBody; Now, in the Start() method, we'll add the

  • Thanks, but I have a couple questions:
  • -Are you suggesting that I should add a Class (for ex: Projectile) which just specifies the Components a basic Projectile is required to have, and then on my Shoot Script Instead of having a public GameObject, create a public Projectile?
  • This is all a bit confusing because I'm more used to OOP development, and I'm never quite sure when to add Classes specifying what a GameObject is, because It always looks like I should just be making a prefab instead. Also can I Instantiate an object in that way if it is In the form of a Script (Projectile class)
  • If you come from OOP it's easier to think of a gameObject as your "root" object which has components (aka. actual classes) attached to it. You rarely instantiate C# objects that don't derive from MonoBehaviour, as they only "work" when attached to a gameObject. In short: attach your classes to your gameObject and instantiate it as a prefab. Regarding my answer: This only works if you have some sort of Script attached to your projectile prefab. If you don't, go with another answer. It would be huge overhead to attach a MonoBehaviour just to require something.
  • It IS hovever good practice to let objects themselves handle their components and just interact with them via their own script. (In your specific example: ProjecileScript handles components and has a method to add velocity which you call from your Shoot class) I don't know if it makes sense in your specific case since, as I already said, MonoBehaviours have huge overhead. If you only handle your rigidbody stuff, don't add a own script to each projectile.