- Home /
JavaScript 3 Arrays questions
Hello guys, I want to start with Unity java script but I can`t understand it even after 2 years Action Script 3 coding. Can you help me? I want to create a 2d array of game objects, so I wrote this:
public var grass:Transform;
public var gameobj : GameObject[];
function Start () {
for (var y = 0.0; y < 10; y++) {
for (var x = 0.0; x < 10; x++) {
var sample = Mathf.PerlinNoise(1, 1);
Instantiate(grass);
grass.transform.position = Vector3 (x, y, 0);
gameobj.Add(grass);
//Debug.Log();
}
}
}
function Update () {
}
But it will not work, I don`t understand why. How do you correctly create game objects from library? How do you push them in arrays?
Answer by robertbu · Oct 04, 2014 at 10:12 PM
You are stuffing the prefab into the array, not the game object you create. Try this:
import System.Collections.Generic;
public var grass:Transform;
private var myList : List.<GameObject> = new List.<GameObject>();
function Start () {
for (var y = 0.0; y < 10; y++) {
for (var x = 0.0; x < 10; x++) {
var sample = Mathf.PerlinNoise(1, 1);
var go : GameObject = Instantiate(grass);
go.transform.position = Vector3 (x, y, 0);
gameobj.Add(go);
}
}
}
Note that your PerlinNoise() will always return the same value the way it is currently being called.
Hi, thank you for your answer. But I`m still getting errors here. CreateWorld.js(25,25): Error BCE0019: 'Add' is not a member of 'UnityEngine.GameObject[,]'. (BCE0019) (Assembly-UnityScript)
You are right. Built-in arrays don't have an Add() method. You need to use a generic list. Here is a quick, untested rewrite. $$anonymous$$ore about the various collections here:
Hmm, it is too difficult to understand it now, I think I need to start with simple things... Do you know any good tutorials for beginners like me?