I’m trying to create tiles and zones. Zones has to dimensional array of tiles. Tiles must has link to zone, but if i will create field "zone link;", this tile will create new zone, and if i will create "ref zone link;", compiler will say "missing ‘(‘ and’)’". Compiler thinks that i am trying to create method that will return reference to zone, but how to create link to zone as field?
(This code written here, not inside any compiler)
using Something;
public class Zone
{
public /*or privet*/ Tile[,]
public Zone(short width, short length)
{
//create Tiles and
//Give "link" to tile as "this"
}
}
public class Tile
{
ref Zone link; //compiler error: missing "(" and ")". he thinks this is method.
//or
Zone link; //logic error: infinite loop where every tile will create new zone.
}
please help me 🙁
i need this for unity, but please, don’t say "unity already has tilemaps"
p.s. sorry if i’m bad at english.
2
Answers
Sounds like you’re coming from C++ here, in which you’d use pointers for this purpose. In C#, classes are Reference Types, so you can just have the following:
Then, the statement
Tile tile = new Tile()
will give you aTile
object that contains a reference to aZone
object. No newZone
will be created when you create a newTile
unless you initialise one with thenew
keyword. You can pass theTile
object you want to store into the constructor for theZone
and assign it there like so:This will give you a reference to the
Zone
that theTile
belongs to.no it will not. It will use whatever
Zone
instance you pass in via the constructor.Since
Zone
is a class which is a reference-type this will re-use the same instance whenever you pass it and actually only store the reference to it.You already can tell this from the keyword
this
which you are passing in aslink
anyway => This always refers to this instance ofZone
=> There is no creation of new instances.In contrary to if it was a
struct
which would then be a value-type, in that case it would indeed create a new copy of the passed value.You simply want e.g.