- Home /
Array won't be filled by Instantiate
Hi guys (and girls ;)),
I just started using Untity and atm I'm fooling around a bit. In this case I'm trying to instantiate grassPrefabs and manage them in an array so I can always check if the player is too far from the grass and it shouldn't be rendered to save ressources, but somehow the array I'm creating stays empty.
I guess the important part is the very last line.
Ty for your help,
RBH
#pragma strict
//Normales Gras
public var Gras1Prefab : Transform;
var grasArray : GameObject[];
//Spieler erstellen
public var PlayerPrefab : Transform;
var iPlayerPrefab : GameObject;
//Level innitiieren.
var newLevel = 1;
public static var GrasColor:Color = new Color(0f, 1f, 0f, 1f);
var mapX : int;
var mapZ : int;
function Start () {
}
function Update () {
//Lade neue Level
if (newLevel==1){
newLevel=0;
iPlayerPrefab = GameObject.Find("PlayerPrefab");
var filePath = Application.dataPath + "/Resources/Textures/Level/Level1.png";
if (System.IO.File.Exists(filePath)){
var bytes = System.IO.File.ReadAllBytes(filePath);
var tex = new Texture2D(1, 1);
tex.LoadImage(bytes);
iPlayerPrefab.transform.position = Vector3 (5,5,5);
transform.localScale += Vector3(tex.width ,0,tex.height);
transform.localPosition += Vector3(tex.width/2,0,tex.height/2);
mapX=tex.width;
mapZ=tex.height;
//Erstellung von "Normales Gras
grasArray = Array(tex.width*tex.height);
for(var x=0; x<tex.width; x++){
for(var z=0;z<tex.height; z++){
var pixel:Color = tex.GetPixel(x, z);
if (pixel==GrasColor){ //Normales Gras
grasArray[x+(tex.width*z)] = Instantiate (Gras1Prefab, Vector3(x,1,z), Gras1Prefab.transform.rotation) as GameObject;
}
}
}
}
}
Answer by fafase · Sep 20, 2014 at 06:06 PM
I am not so used to UnityScript anymore but I would think you need to instantiate your array. You have a reference for an array of type GameObject but you never tell how many spot it should have:
var grasArray = new GameObject[size];
The big advantage of UnityScript over C# is that it does not seem to let you know you are doing wrong and then you are up for some long hours while C# would have told you right on that this array is not existing.
That's what i wanted to do in Line 42:
grasArray = Array(tex.width*tex.height);
but even if I change it to your solution, there is no difference. Also I looked the array up with both options, it always had the right size (in this case 1024 because the mapsize ist 32*32), but is always just empty.
Well, I made a workaround by not managing all gras together but every by itself by adding a new script. Not what i wished for, but also works.
Ty :)