- Home /
Instantiate Prefab from within class
I'm having a bit of difficulty figuring this out, but I think I am overlooking something simple.
I had my script for a level generator which would instantiate prefabs to build the level. It followed this pattern, just in the root of the .js file which I attached to a blank object in the scene.
public var wall : Transform;
function Start () {
for (var x = 0; x < 10; x++){
var newTile : Transform;
newTile = wall;
var instTile : Transform = Instantiate(newTile, Vector3(x, 0,0),Quaternion.identity);
}
}
At which point I drag the prefab onto the script variables area in the Inspector.
However, I want to create a class that will do the instantiating. I know that I need to use GameObject.Instantiate, but my issue comes from not having the Prefabs available within the class.
If I create a class and try to access the prefabs, it says it cannot recognize the prefabs.
Here is an example of what I was trying using classes:
public var wall : Transform;
class area{
function area(){
var newTile : Transform;
newTile = wall;
var instTile : Transform = GameObject.Instantiate(newTile, Vector3(x, 0,0),Quaternion.identity);
}
}
function start(){
var currentZone = new area();
}
Which tells me that there is no such object as "wall". If I declare the prefabs within the class, I can no longer drag them onto the script in the Inspector Panel.
Am I missing something obvious here?
Answer by dai1741 · Sep 30, 2011 at 08:28 AM
As far as I understand, an inner class is not able to access the outer class' variables implicitly in UnityScript. You can access them by supplying the outer instance explicitly, it's not so elegant though.
Here's a fixed script:
public var wall : Transform;
class area{
var outer;
function area(_outer) {
outer = _outer;
var newTile : Transform;
newTile = outer.wall;
var instTile : Transform = GameObject.Instantiate(newTile, Vector3(0, 0,0),Quaternion.identity);
}
}
function Start(){
var currentZone = new area(this);
}
Thanks, that does work. I hadn't known you could pass the outer class like that!
Answer by thor_tillas · Sep 30, 2011 at 08:16 AM
There is two ways to spawn some prefab on the fly.
First one : Use a list of public members which describe each prefab you need for your level and spawn them in the start or awake function. For example (sorry, but I can't write js script... I hope you are able to translate C#):
public class LevelLoader : MonoBehavior
{
public Transform WallPrefab;
public Transform EnnemyPrefab;
protected void Start()
{
GameObject wallObject1 = GameObject.Instanciate(this.WallPrefab);
GameObject wallObject2 = GameObject.Instanciate(this.WallPrefab);
// ...
}
}
Or you can use the Resources.Load() method. Put your wall prefab in the Resources folder and then use the load function to instanciate your prefab.
Hope it's helped...
cheers, Thor
Your answer
