- Home /
Using Variables from Parent Class (And Instantiate)
Hey everyone!
I have an array of custom objects representing tiles on a board. Inside each object is a function to instantiate a prefab. For some reason, this function works well when it's in a script in the Start() function of my game controller, but not when it's buried in the class.
When compiled, Unity tells me that it can't find tilePrefab
, TileArray
, and it has no clue what Instantiate
is.
I know that this is an obvious problem but I can't quite figure it out.
The stipped-down version of the code in question:
// In GameController.js
public var tilePrefab : Object;
public var TileArray : Tile[,];
function InitialGridLoadup (){
tilePrefab = Resources.LoadAssetAtPath("Assets/Prefabs/Tile/Tile.prefab", Object);
for ( var x : int = 0; x < mapX; x++ ) {
for ( var z : int = 0; z < mapZ; z++ ) {
// Creates the tile
TileArray[x, z] = new Tile(type, false, 10, x, z);
TileArray[x, z].CreateTile();
}
}
}
class Tile{
var type : int;
var visible : boolean = false;
var health : int;
var x : float;
var z : float;
function CreateTile () {
switch (type){
case 0 :
var tile : Transform = Instantiate(tilePrefab.transform, new Vector3(x,0,z),Quaternion.identity);
tile.name = TileArray[x, z].Name();
break;
}
}
As a super added bonus, does anyone know a streamlined way to replace a GameObject with another prefab at runtime? I need a function here to replace one type of tile with another.
I tried your script and it seems to me that static functions have to be called statically when inherited by a UnityScript class (i.e., Object.Instantiate rather than simply Instantiate). As for the variables not being recognized, it's because a script written in UnityScript is implicitly treated as its own class (like the explicit class declaration in C#). Obviously, that would make them outside the scope of another class, even if that class is found in the same script.
Good call. I need the variables to be declared in a parent though, because I get the feeling that loading the prefab asset for every instance of the tile class is going to hit it really hard.
It seems to me that you're not instantiating this particular script and that you don't really need tilePrefab and TileArray to be serialized, so you can just make those variables static.
Answer by testure · Jun 24, 2011 at 08:48 PM
Instantiate is a member of MonoBehaviour, you can't just call it from a class that's not derived from it. If you're using a singleton game manager, you cold make a static function called Instantiate and call it using GameManager.Instantiate
other than that, you're going to have to find another way to do what you're trying to do.
Instantiate is only an inherited member of $$anonymous$$onoBehaviour. It is inherited from System.Object, which all classes derive from, so every class has Instantiate.
Your answer
