Is there a way to store an array in one script and access it in another?
I want to store an array of tile locations in one script where I can save the data and then have another script where it can decode the quads name and match it to find the array.
So I have a set of arrays named under a float land
. Also in the process of generating the map I named the cloned quads (tiles) equal to the set of arrays. Thus allowing me to store data in an array and access it in each of the individual tile scripts. I am having a hard time finding bits of scripts that will work with each other. The way it should work in the other script is that it should get the tiles names and try to find its match in the array.
using UnityEngine;
using System.Collections;
public class mapGenerator : MonoBehaviour {
public Transform tilePrefab;
public Vector2 mapSize;
public float[][] land;
[Range(0,1)]
public float outlinePercent;
void Start(){
genMap ();
}
void Awake(){
// initializes the first part of the array according to the mapsize.x
land = new float[(int)100][];
// loops through to initialize to represent the y
int i = land.Length;
while (i > 0) {
i--;
land [i] = new float[(int)100];
}
}
public void genMap(){
string holderName = "Generated map";
string tileId;
float calculation;
//allows the script to be edited and saved during play
if (transform.FindChild (holderName)) {
DestroyImmediate (transform.FindChild (holderName).gameObject);
}
//makes a "folder" for the tiles
Transform mapHolder = new GameObject (holderName).transform;
mapHolder.parent = transform;
//map generator. Every for each row It fills the row with tiles
for (int x = 0; x < mapSize.x; x++) {
for (int y = 0; y < mapSize.y; y++) {
//makes and moves a single new tile
Vector3 tilePos = new Vector3 (-mapSize.x / 2 + 0.5f + x, 0, -mapSize.y/2 + 0.5f + y);
Transform newTile = Instantiate (tilePrefab, tilePos, Quaternion.Euler(Vector3.right*90)) as Transform;
//makes an outline
newTile.localScale = Vector3.one * (1 - outlinePercent);
//puts it in the file
newTile.parent = mapHolder;
//names the tile based on its chordinate
tileId = "" + ((x*mapSize.y)+y) + "";
newTile.name = tileId;
}
}
}
}
By the way there are 10,000 tiles so this is kinda necessary to store the data.
What exactly is the question? How to access "land" in other scripts?
Yes. I need to access the array in another script.
Answer by Major · Jun 28, 2017 at 03:51 AM
Use GetComponent like you would for any other value, or set a variable of type mapGenerator is whatever script you need to access the values from, and set it to the instance you need (a gameobject with this script applied).