Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Instantiate a GUIImage as a Child, Problems

Discussion in 'Scripting' started by MG, Jul 12, 2016.

  1. MG

    MG

    Joined:
    Nov 10, 2012
    Posts:
    190
    When I spawn the Image, its been placed in the hierarchy outside of the canvas. I have som child of child of child, in the canvas, and I want it be instantiated as a child for a specific parent.

    This is the code

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class SpawnItemForInventory : MonoBehaviour {
    5.     public GameObject[] Items;
    6.     public GameObject DenSelv;
    7.     // Use this for initialization
    8.     void Start () {
    9.         DenSelv = this.gameObject;  
    10.     }
    11.  
    12.     public void AddItem (int ItemNumber)
    13.     {
    14.         Transform go = Instantiate(Items[ItemNumber], this.transform.position, Quaternion.identity) as Transform;
    15.         go.transform.parent = DenSelv.transform;
    16.     }
    17. }
    18.  
    Im getting this every when AddItem function is called from outside:

    Code (CSharp):
    1. NullReferenceException: Object reference not set to an instance of an object
    2. SpawnItemForInventory.AddItem (Int32 ItemNumber) (at Assets/SpawnItemForInventory.cs:20)
    3. UnityEngine.GameObject:BroadcastMessage(String, Object)
    4. BuyItem:Buy() (at Assets/BuyItem.cs:24)
    5. UnityEngine.EventSystems.EventSystem:Update()
    I would like to mention that it instantiates the right prefab, just at the wrong "location"

    Do you know what is wrong?
     
  2. SkaredCreations

    SkaredCreations

    Joined:
    Sep 29, 2010
    Posts:
    296
    "as Transform" is just wrong, since Instantiate should return a GameObject:

    Code (CSharp):
    1. Transform tfm = Instantiate<GameObject>(Items[ItemNumber]).transform;
    2. tfm.SetParent(DenSelv.transform)
    3. tfm.localPosition = Vector3.zero;
    4. tfm.localRotation = Quaternion.identity;
    5.  
     
  3. MG

    MG

    Joined:
    Nov 10, 2012
    Posts:
    190
    Thanks SkaredCreations

    It worked!