Search Unity

Attaching a Prefab to a Script without using the Unity UI.

Discussion in 'Scripting' started by QuinnDP, Jan 18, 2017.

  1. QuinnDP

    QuinnDP

    Joined:
    Dec 12, 2016
    Posts:
    22
    I have started to make a breakout game (got to start somewhere right?), complete with menu system and multiple levels. Whilst building the game itself, I have focused on writing the code so that on duplication of the levels, I do not need to reconnect any items through the Unity UI (for example, the bouncing ball makes reference to the paddle's transform to stay on the paddle till launching, but I didn't want to tell every level's ball where that levels paddle was).

    I have had some problems with duplicating the Ball however, so that if you were to drop a ball it would take 1 life away and continue with a new ball. To spawn a new ball, I must (presumably) make an Object ballPrefab, reference that Object to the Prefab, then instantiate the ballPrefab whenever the ball drops. I've been unable to make the Object "ballPrefab" link to the prefab itself.

    I have tried (with no prevail as of yet) the following:

    Code (CSharp):
    1. ballPrefab = Resources.Load("Ball.prefab");
    2. ballPrefab = EditorUtility.FindAsset("Assets/Prefabs/Ball.prefab", typeof(GameObject));
    3. ballPrefab = AssetDatabase.LoadAssetAtPath("Assets/Prefabs/Ball/", typeof(GameObject));
    • For Resources.Load I placed the Ball Prefab into Assets/Resources/ as required.
    • For LoadAssetAtPath I tried creating a Ball folder within Prefabs, with the Ball.prefab file being the only file inside.

    All 3 of these methods have ended with the same error, "The prefab you want to instantiate is null". Any chance for a tip or two as to where I'm going wrong here?
     
  2. BrokenAngel

    BrokenAngel

    Joined:
    Mar 24, 2013
    Posts:
    92
    Try Resources.Load("Ball"); since unity assets at Resources folder is an imported assets not a file , it doesnt need an extensions.
     
    QuinnDP likes this.
  3. QuinnDP

    QuinnDP

    Joined:
    Dec 12, 2016
    Posts:
    22
    This seems to work, Thanks! For anyone else reading with familiarity to the other 2 commands I would very much appreciate knowing why these both also fail, but this definitely solves the problem for now, thanks!
     
  4. BrokenAngel

    BrokenAngel

    Joined:
    Mar 24, 2013
    Posts:
    92