Search Unity

Instantiate prefabs by different types?

Discussion in 'Scripting' started by Chrisbii, Nov 27, 2014.

  1. Chrisbii

    Chrisbii

    Joined:
    Oct 28, 2014
    Posts:
    9
    I feel this is very basic, but I just can't figure it out.

    In this video:


    The script looks like this

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class UsingInstantiate : MonoBehaviour
    5. {
    6.     public Rigidbody rocketPrefab;
    7.  
    8.     void Update()
    9.     {
    10.         if(Input.GetButtonDown("Fire1"))
    11.         {
    12.             Instantiate(rocketPrefab);
    13.         }
    14.     }
    15. }
    The "rocketPrefab" is initialized as a Rigidbody, but the prefab is a GameObject, maybe with a Rigidbody attached, isn't it?

    Why do this code not initialize "rocketPrefab" as a GameObject?

    I am trying to do this:
    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class Spawn : MonoBehaviour {
    5.    
    6.     public GameObject prefab;
    7.    
    8.     void Start () {
    9.  
    10.         GameObject test = Instantiate (prefab) as GameObject;
    11.         test.tag = "TagName";
    12.     }
    13.    
    14.     // Update is called once per frame
    15.     void Update () {
    16.  
    17.     }
    18. }
    The prefab is Instantiated, but I can't set the tag name?

    As mentioned, would it be nice to understand this. I feel I lack some basic understanding.

    Thanks
     
  2. jiangjiang

    jiangjiang

    Joined:
    Feb 17, 2014
    Posts:
    6
    u should check if u have the Tag named "TagName"
     
  3. Chrisbii

    Chrisbii

    Joined:
    Oct 28, 2014
    Posts:
    9
    I have. The error I get is this:

    "NullReferenceException: Object reference not set to an instance of an object"
     
  4. jiangjiang

    jiangjiang

    Joined:
    Feb 17, 2014
    Posts:
    6
    if u have the prefab?it means the prefab is null;
     
  5. Chrisbii

    Chrisbii

    Joined:
    Oct 28, 2014
    Posts:
    9
    But the prefab is Instantiated and live on my scene. Should "test" not be a direct reference to the GameObject?
     
  6. Chrisbii

    Chrisbii

    Joined:
    Oct 28, 2014
    Posts:
    9
    I had to call it like this

    test.gameObject.tag = "TagName";