unity 3d student

Beginner B05 – Instantiate to Create Objects

How to create objects in your scene during runtime using Prefabs and the Instantiate() command.

Code Used

//Simple Instantiation of a Prefab at Start
  1. var thePrefab : GameObject;
  2.  
  3. function Start () {
  4.  var instance : GameObject = Instantiate(thePrefab, transform.position, transform.rotation);
  5. }

Further Reading

Share via Social Media

  • Digg
  • StumbleUpon
  • del.icio.us
  • Facebook
  • Yahoo! Buzz
  • Twitter
  • Google Bookmarks
  • Add to favorites

39 Comments

    I used the following script:
    var thePrefab : gameObject;

    function Update () {

    if(Input.GetButtonUp(“Jump”)){
    var instance : gameObject = Instantiate(ThePrefab, transform.position, transform.rotation);

    }
    }

    I got the following error:
    BCE0018: The name ‘gameObject’ does not denote a valid type. Did you mean ‘UnityEngine.GameObject’?

    • u must type GameObject, not gameObject

    you need a big G in Gameobject, thats your problem.

    • and you are missing a big O in your GameObject.

      • var thePrefab:GameObject
        Instantiate(thePrefab)

    I tried to instantiate an object when I pressed space, but it instantiated the object every frame I had the space button pressed in, so I used this script (se below) to make it only instantiate it one time, is there a bether way to make it only instantiate it one time?

    //Simple Instantiation of a Prefab when a button is pressed
    var thePrefab : GameObject;
    var ObjectLimit = 1;
    var InstantiatedObjects = 0;

    function Update () {
    if (Input.GetButton(“Jump”)) {
    //Check if the prefab already has been instantiated
    if (InstantiatedObjects < ObjectLimit) {
    var instance : GameObject = Instantiate(thePrefab, transform.position, transform.rotation);
    InstantiatedObjects ++;
    }
    }
    }

    • Simen, I think using GetButtonUp instead of GetButton might fix your problem. I think using just GetButton means it’ll check if the key or button is currently being pressed every frame and carry out whatever you set it to do. If you use GetButtonUp, it still checks every frame but it checks if the key/button has been both pressed and released so only executes whatever you told it to do (in this case instanciate an object) once until you press the key again instead of once each frame..

      • Couldn’t have put it better myself! Excellent stuff Aaron!

      • Thanks a lot aaron:)

    Hi everyone, I kept the objectLimit++ incrementing variable outside the if statement, else it would’nt work..

    var Box2 : GameObject;
    public var objectLimit : int = 0;
    public var objectadd : int = 5;

    function Update () {

    if(Input.GetButtonUp(“Jump”)){

    var instaceBox2 : GameObject = Instantiate(Box2, transform.position,transform.rotation);

    if(objectLimit > objectadd){
    Destroy(gameObject.Find(“Wall”));
    }
    objectLimit++;
    }

    }

    • Some people find destroying children quite tricky but it can be done with one line of code obviously using Destroy method and looping through transform property of parent object. Check this post. I posted code in c# and JS.

    Hi,

    I am trying to find a property of the instantiated objects to find them with. Suppose i make a prefab named bullet and i shoot(Instantiate) some it in the game. Later i want to find them again, a guy comes by with a big magnet or something 😉 How can i query for a instantiated object of the prefab bullet? What i do know is search for “bullet(Clone)” it works but it isn’t very clean.

    Regards,
    Deg

    • Hi Deg

      well if you want to address something you’ve just created you’ll create a variable for the instantiation, like this –

      var thingToMake : GameObject = Instantiate(prefab, transform.position, transform.rotation);

      then you can do what you like to that variable and it’ll address the recently made instance of the prefab –

      thingToMake.name = “bullet”;

      the above would name it so that it won’t be named like the prefab with ‘(Clone)’ on the end. Alternatively if you’re firing differently named objects you could tag them with a particular tag, and then find objects with that name.

      Moving on from that you could add the bullet to an array but I’m not too sure why you’d really need to do something like that for a bullet.

      • It is more in general really, i try to avoid globals as much as possible. So when I, at point A in the game, instantiate prefabs in the game without storing any references to them. Can I, at point C in the game, find them again? I guess I got spoiled by collection based programming such as python & jquery. There is a lot of caching going on in the background there though, it is probably better to store references right away in unity.

        Anyway the tagging is something I can dive into together with some reading up on globals handling in unity.

        cheers,
        Deg

    I try to do the same in C# but it’s not working
    Someone can do this in C#?

    • Can you post what you have to http://www.pasteit4me.com, and then post the link back here in the comments and we’ll do our best to tell you what you have done wrong.

    • Here is the C# code…

      using UnityEngine;
      using System.Collections;

      public class Creator : MonoBehaviour {

      public GameObject thePrefab; //Needs to be declared as public to be seen in editor

      // Use this for initialization
      void Start () {
      GameObject instance = new GameObject();
      instance = Instantiate(thePrefab, transform.position, transform.rotation) as GameObject;
      }
      }

      • This was just what I was looking for, I struggled with this for a while.
        Now I can finally instantiate my bullets how I want to!

        • Ow, the “GameObject instance = new GameObject();” part creates empty gameobjects for me. I changed it to:
          GameObject instance = Instantiate(thePrefab, transform.position, transform.rotation) as GameObject;
          And now it works fine.

        Thanks so much, it gets so hard sometimes trying to copy what he does in java into C# but you helped a lot. Thanks again!

      • Thank you, this help me a lot.

    Hi Will,

    This is the father of the Bob Berkebile (Pixelplacement) that you know. I’m working with my son and trying to learn this stuff.

    These are excellent training videos, easy to follow, easy to understand. One thing that would help me personally is if you could also provide the code in C# in addition to Javascript.

    Anyway, thanks again.

    • Hi there Mr B, great to hear from you. Providing the C# equivalent is something I’ve always meant to do but kept putting on the backburner in favour of ideas for new content – but for you I’ll put it on the new years resolution list to get done as swiftly as possible. I certainly owe you for making such a productive progeny in the realms of highly useful Unity freebies!

    I’m a little confused with variables. I thought a var was just for storing values, but here the var line seems to be taking action and instantiating the object.
    I also tested that by re-defining the variable, it would create another copy of the prefab. (instance = Instantiate(thePrefab, transform.position+Vector3(10,10,10),transform.rotation);)

    What exactly is happening here? Which part actually says “Make a new object”?

    • … Instantiate(thePrefab, transform.position, transform.rotation)
      This function says make a new object based on “thePrefab” located at the position of the GameObject the script is attached to (transform.position) and rotated to match the alignment of the GameObject the script is attached to (transform.rotation).

      var instance : GameObject = …
      The function also returns a reference to the newly created GameObject so that is why it is assigned to instance which just so happens to be declared on the same line.

    this is what I did.

    var thePrefab : Transform; // so I can access it and link an object.

    function Start() {
    instance = Instantiate(thePrefab,transform.position, transform.rotation);
    instance.name=”Somename”;
    }

    and in c#

    using UnityEngine;
    using System.Collections;

    public class CreatorCS : MonoBehaviour {

    public Transform thePrefab;

    void Start () {

    Instantiate(thePrefab, transform.position, transform.rotation);
    }
    }

  • Hi everyone, I have a couple of bouncy cubes inside 4 walls. I am trying to instantiate a cube each time any of the cubes do bounce against any of the walls. Here’s my code:

    var thePrefab : GameObject;

    function OnCollisionEnter(theCollision : Collision) {

    if (theCollision.gameObject.name == “Wall”)
    {

    var instance : GameObject = Instantiate (thePrefab, transform.position, transform.rotation);

    }

    }

    Problem is, it is not instantiating, is there some error within my code? Thank you!

    P.S. Console does not give me any errors.

  • Typed in code, drag/drop script onto GameObject but keep getting following error:
    UnassignedReferenceException: The variable thePrefab of ‘Creator’ has not been assigned.
    You probably need to assign the thePrefab variable of the Creator script in the inspector.

    Any ideas on what is wrong?

    Thanks,
    -GmG-

  • Suppose that i have an empty object and that i have two prefabs.One that contains a cube and one that contains a sphere. First, assign cube to empty object and whenever Jump key is pressed, i want to my empty project to swap prefabs. ( E.x if it is cube , become sphere , otherwise become cube )
    how can i do that?

  • I’ve followed this exactly (using Unity 4.1) and I don’t get the “thePrefab” variable in my Inspector (although I so have the creator script there) so I can’t drag my prefab onto it.

    Has it changed in Unity 4.1?

  • Hi there, I love these modules, I cannot thank you enough for making them! I’ve typed in the code used in these videos, but for some reason my instantiated cube does not retain the transform.rotation property. The original bouncyBox prefab is rotated slightly to maximize the bounce collision effect, just like you have in the video, but the instantiated prefab contains none of the rotation, it’s being a square (pardon the pun, couldn’t help myself!)

    Here’s the code I’ve attached to the empty game object, using my bouncyBox prefab as the assigned GameObject variable in the script; am I doing something wrong?

    var prefab : GameObject;

    function Start () {
    var instance : GameObject = Instantiate(prefab, transform.position, transform.rotation);
    }

  • var thePrefab: GameObject
    Instantiate(thePrefab)not a ThePrefab u take both same spelling

  • Where/How do people learn all of this? I can’t find anything that learns me javascripting like telling me what everything does (what var means/does, why there needs to be a ; at the end of most lines and more like that

  • Okay, so when I do this (and I’ve copied the code directly from his video, as well as everything else I get “NullReferenceException: Object reference not set to an instance of an object Create.Start () (at Assets/Create.js:3)” Can anyone please explain what’s wrong? Here is my code

    var thePrefab : GameObject;
    function Start() {
    var instance : GameObject = Instantiate(thePrefab, transform.position, transform.rotate);
    }

    • it should be ‘transform.rotation’ not ‘transform.rotate’ as you put it. So you didn’t copy it directly 😉 easy mistake to make but rotation is a value where ‘Rotate’ (caps) is a function to perform rotation.

    hi there i have done every tutorial up to this point but cannot get any script to work, i have copied and pasted every code and followed instructions to the letter. when i click play i dont get any message errors but no code works
    any ideas?

    thanks

  • error CS0103: The name `thePrefab’ does not exist in the current context

  • this is my version of the script it works as expected but is there anyway to return the rigidbody component on the clone instead of having to hold a reference to it?

    my script:
    http://pastebin.com/9Wvt86Ak

Leave a Comment