Search Unity

Accessing Prefabs from in scripts

Discussion in 'Scripting' started by skyhawk, Jun 1, 2006.

  1. skyhawk

    skyhawk

    Joined:
    Jun 13, 2005
    Posts:
    49
    After spending 3 days learning all the quirks and ends and outs of Unity I could from the documentation (which by the way, yall have done a WONDERFUL job of doing (still needs more though :eek: ), I've stumbled upon a problem.

    In my .cs script, I am trying to spawn a bullet prefab. From the examples shown, it was saying to do something similar to this:
    Code (csharp):
    1. if(firecounter == 1)    // first shot fire
    2. {
    3.    totalshots++;
    4.    //shot = new GameObject ("shot" + totalshots);
    5.    // spawn one object in the middle front of me
    6. }
    7. ...
    and add components to it... but I never found out how to add a model to that, so I threw that out.

    I then looked up and it said something about use Object and Instantiate and use such... but it kept throwing up an error saying it couldn't find my bullet prefab.

    Any suggestions as to what I'm doing wrong?
     
  2. Joachim_Ante

    Joachim_Ante

    Unity Technologies

    Joined:
    Mar 16, 2005
    Posts:
    5,203
    Did you assign the prefab to a public variable?

    something like:
    Code (csharp):
    1.  
    2. class ...
    3. {
    4.   public Transform bullet;
    5.  
    6.  void Start ()
    7.  {
    8.     Instantiate(bullet);
    9.  }
    10. }
    11.  
    When using this kind of script you of course also have to assign a reference to the prefab in the inspector. So that the script knows what object to instantiate.
     
  3. skyhawk

    skyhawk

    Joined:
    Jun 13, 2005
    Posts:
    49
     
  4. Joachim_Ante

    Joachim_Ante

    Unity Technologies

    Joined:
    Mar 16, 2005
    Posts:
    5,203
    Transform is good for this purpose.