- Home /
Access a variable of a class stored in an array.
Ok, so I am still new to classes, but I am trying to use it in a pathfinding script. I've started off trying to use a script from a tutorial, but it was in C# and I really just needed to know the grid creation method. So now I have a class.
class GridCell
{
var cellWalkable: boolean;
var cellHeight: float;
var cellX: float;
var cellZ: float;
var transformPosition: Vector3;
}
This class is created multiple times to form the grid.
for(var x = 0; x < mapWidth; x++)
{
for(var y = 0; y < mapHeight; y++)
{
//Gets the position for a ray
var currentPosition = topLeftCorner + Vector3(x * cellSize, 0, y * cellSize);
var hit: RaycastHit;
//Creates a cell for the grid
var cell = new GridCell();
//Cast the ray
if(Physics.Raycast(currentPosition, Vector3(0, -1, 0),hit, bounds.size.y))
{
if(hit.transform.gameObject.layer == walkableLayer)
{
cell.cellHeight = hit.point.y;
cell.cellX = hit.point.x;
cell.cellZ = hit.point.z;
cell.transformPosition = Vector3(cell.cellX, cell.cellHeight, cell.cellZ);
cellArray.Push(cell);
}
}
}
At the end of that, I pushed all of the cells into an array called cellArray. In another script called ZombieScript, I am trying to get the transformPosition variable of the cell. I am currently trying to use this.
function UpdateGrid()
{
var currentNode;
var nearestDistance = Mathf.Infinity;
for(var i = 0; i < navCubeScript.cellArray.length; i++)
{
if(Vector3.Distance(transform.position, navCubeScript.cellArray[i].transformPosition) < nearestDistance)
{
}
}
}
The problem I get, however, is that I get an error saying this.
'transformPosition' is not a member of 'Object'.
Does anyone have any idea how to get a work around this? Thanks! :D
Answer by Chronos-L · Apr 18, 2013 at 06:20 AM
You are using the Javascript array, which is "untyped", so the elements are stored as Object
. So, when you access the element, you need to cast it to a GridCell
to use transformPosition
.
...
for(var i = 0; i < navCubeScript.cellArray.length; i++)
{
if(Vector3.Distance(transform.position, ( navCubeScript.cellArray[i] as GridCell ).transformPosition) < nearestDistance)
{
}
}
...
I would recommend you to switch to List < GridCell >
as it is dynamic, and has better performance. If you need it to have mixed type, like what a Javascript array is, you can use List < Object >
.
Reference:
Answer by Eric5h5 · Apr 18, 2013 at 06:16 AM
Never use the JS Array class; use built-in arrays ideally (like GridCell[]
), or a generic List (like List.< GridCell >
) if it has to be a dynamically-sized array.
Your answer
![](https://koobas.hobune.stream/wayback/20220613100535im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How to delete new'd arrays? 2 Answers
TextAsset inside the Array - UnityScript/JavaScript 1 Answer
JS Array Object to Float 1 Answer
How do i check if all tagged objects are inactive? 2 Answers
How do you debug arrays of objects? 1 Answer