Hello Guest

Author Topic: Trying to instantiate a prefab at runtime, but can't find where to associate it  (Read 8558 times)

ErayMan

  • 2D Toolkit
  • Newbie
  • *
  • Posts: 2
    • View Profile
Hi! I am new to Unity & 2d Toolkit.
I am trying to Instantiate a new Sprite when Space is pressed.
I have a spaceship (which is an AnimatedSprite) and in the script (C#) associated I have:

Code: [Select]
...
Transform Bullets;

// Use this for initialization
void Start () {
}

// Update is called once per frame
void Update () {

if (Input.GetKeyDown(KeyCode.Space))
{
Instantiate(Bullets, Vector3.up, Quaternion.identity);
                }
        }
...

Now it compiles without problem. If I understand correctly, in the Unity's Inspector, while selecting my AnimatedSprite, I should be able to see "Bullets" as an updatable field and be able to select which gameobject I want to use as "Bullets"
Unfortunatly, I cannot find any trace of "Bullets" anywhere in Unity except in the warning telling me that Bullets is never assigned to and will use default value "null".

How can I assign a gameobject (or a Sprite, I assume?) to my global variable "Bullets" declared in the behavior script of an AnimatedSprite?
Thanks

unikronsoftware

  • Administrator
  • Hero Member
  • *****
  • Posts: 9709
    • View Profile
It needs to be public to appear in the inspector....

public Transform bullets;

Why are you instantiating it at Vector3.up? That will instantiate it at (0, 1, 0). You probably want transform.position + offset, to get it to spawn at the correct place. Alternatively, add an empty object to mark where to spawn it, and attach that transform to do it - that way you won't have to worry about rotations, etc.

ErayMan

  • 2D Toolkit
  • Newbie
  • *
  • Posts: 2
    • View Profile
Quote
It needs to be public to appear in the inspector....

public Transform bullets;

Haha yeah, it slipped my mind... it just goes to show that sometime all you need is to take a step back to see the obvious :)
I'll also look into the transform.position + offset, as the vector.up was just a placeholder for me.

Thanks for your help Unikron; you really are an one man army around here! ;)