- Home /
transform.position error
Hey there. I have a system set up that creates an array of objects that forms a grid. I'm trying to make the grid start on the position of the gameObject that it's attached to, but I'm having trouble referring to the gameObject. Here's my code.
using UnityEngine;
using System.Collections;
public class GridCreator : MonoBehaviour
{
public int width = 10;
public int height = 10;
public Cell[,] cells;
public GameObject unit;
public class Cell
{
public Vector3 pos;
public int sizeMod = 1;
public Cell(int x, int y)
{
pos = new Vector3((x*sizeMod)+gameObject.transform.position.x,0,(y*sizeMod)+gameObject.transform.position.y);
}
}
void Awake ()
{
cells = new Cell[width, height];
for (int y = 0; y < height; ++y)
{
for (int x = 0; x < width; ++x)
{
cells[x,y] = new Cell(x, y);
GameObject newunit = Instantiate(unit, cells[x,y].pos, Quaternion.identity) as GameObject;
}
}
}
}
The grid works and instantiates Units correctly if I take the additives (+gameObject.transform.position.x/y) out of the equation here
pos = new Vector3((x*sizeMod)+gameObject.transform.position.x,0,(y*sizeMod)+gameObject.transform.position.y);
But when I leave them in I get this error
Cannot access a nonstatic member of outer type `UnityEngine.Component' via nested type `GridCreator.Cell'
Am I trying to access the variable incorrectly? Not sure what I'm doing wrong. Thanks for any help.
Answer by Owen-Reynolds · Oct 12, 2012 at 07:46 PM
The rule causing the problem is that classes can only use things "inside" of them. `Cell` can't use globals `width` or `GameObject` like a function would be able to, since `Cell` isn't really part of `GridCreator` (some other script could make some cells, but have no gridCreator anywhere in the scene.)
Maybe change the constructor: `public Cell(gameObject myBase, float x, float y);` Might also move `sizeMod` up into Grid.
What some people do is have a back pointer, so Cell would have `GridCreator mygrid;`, set at creation, and could use `myGrid.gameObject`. But not worth it for just cells.
Hey, thanks a lot! That really helps. I think a lot of my problems are caused by confusing classes and functions- I'm going to do some reading on that subject.
Anyways, everything made sense besides the 'back pointer' section- not really sure what you meant by that.
Your answer
Follow this Question
Related Questions
Take final position after a force applied to a GameObject 1 Answer
Locating Position of Object not Working? 2 Answers
Need insight on strange (simple) 2D object transform bug 0 Answers
Can i transform the position of an object to another object? 1 Answer
[CODE]Keep Gameobject position exactly at mouse cursor when cast float position to int 1 Answer