skip to Main Content

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


  1. 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:

    public class Tile
    {
        Zone ParentZone;
    }
    

    Then, the statement Tile tile = new Tile() will give you a Tile object that contains a reference to a Zone object. No new Zone will be created when you create a new Tile unless you initialise one with the new keyword. You can pass the Tile object you want to store into the constructor for the Zone and assign it there like so:

    public Tile (Zone parent)
    {
       ParentZone = parent;
    }
    

    This will give you a reference to the Zone that the Tile belongs to.

    Login or Signup to reply.
  2. if i will create field "zone link;", this tile will create new zone

    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 as link anyway => This always refers to this instance of Zone => 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.

    public class Tile
    {
        public Zone link { get; }
    
        public Tile(Zone link)
        {
            this.link = link;
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search