- Home /
Instantiate, Prefabs, Classes
I'm trying to do some basic OOP, I'm just not sure how I'm supposed to do it.
In main.js I want to make an array of Tile
Tile is a prefab, but should also be its own javascript class with it's own methods and properties and instantiated game object.
What type of script do I need to attach to the Tile prefab to give it methods like test. And how should I instantiate each Tile in its constructor? I want to do something like this (none of this works right now):
 private var tiles:Tile[,];
 for(var x=0;x<width;x++) {
     for(var z=0;z<width;z++) {
         var tile:Tile = new Tile(x, z);
         tiles[x,z] = tile;
         tile.test(); // each tile should have this method which just does Debug.Log('test')
     }
 }
Answer by farzher · Sep 11, 2013 at 02:51 AM
So, I finally came up with an alright solution to this, after looking up a million things. This is way more complicated than it should be.
 public static Tile Instance (int something) {
     GameObject go = (GameObject)Instantiate(Resources.Load("Tile"));
     Tile instance = go.GetComponent<Tile>();
     instance.something = something;
     return instance;
 }
Now I can just do this wherever
 Tile tile = Tile.Instance(5);
 tile.test();
Trying to do this stuff in the constructor doesn't work.
You are trying to create a MonoBehaviour using the 'new' keyword. This is not allowed.
So I had to make my own arbitrary static Instance method. I have to be missing something, this seems like a total hack.
Your answer
 
 
             Follow this Question
Related Questions
How can I instantiate more prefabs as the score increases? 2 Answers
Prefabs double at each instance? 1 Answer
Prefab Cannot Select Object Correctly 0 Answers
Access a script that has NO class? 2 Answers
Prevent instantiating on collider 1 Answer
 koobas.hobune.stream
koobas.hobune.stream 
                       
                
                       
			     
			 
                