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. Dismiss Notice

Why is this giving me a error?

Discussion in 'Scripting' started by Stef_Morojna, Nov 7, 2016.

  1. Stef_Morojna

    Stef_Morojna

    Joined:
    Apr 15, 2015
    Posts:
    289
    This is the script:

    All I want to do instantiate the object texture, and then have a reference to its sprite renderer.
    public Transform texture;

    Code (CSharp):
    1.  
    2. public Transform texture;
    3.  
    4. void CreateGrid(/*int w, int h, int[] info, Vector2 offset*/){
    5. GameObject refer = Instantiate(texture, Vector3.zero, Quaternion.identity, transform) as
    6. GameObject;        
    7. SpriteRenderer sprite = refer.GetComponent<SpriteRenderer>();
    8. }
     

    Attached Files:

    Last edited: Nov 7, 2016
  2. Endalth

    Endalth

    Joined:
    Oct 13, 2016
    Posts:
    11
    I think texture needs to be a GameObject not a Transform.
     
  3. KelsoMRK

    KelsoMRK

    Joined:
    Jul 18, 2010
    Posts:
    5,539
    texture is a transform but you're trying to cast the instantiated copy of it as a GameObject. "as casts" return null if the cast fails - which it is in this case.
     
  4. Stef_Morojna

    Stef_Morojna

    Joined:
    Apr 15, 2015
    Posts:
    289
    Thanks!

    So at the end what I did was this:

    Code (CSharp):
    1.  
    2. sprite = ((Transform)Instantiate(texture, pos, Quaternion.identity, transform)).GetComponent<SpriteRenderer>();