Sign in to follow this  
Adehm

Unity [Unity] Arrays

Recommended Posts

I'm new to Unity and trying to store dynamic public variable arrays to be used throughout my project. I declare my array inside of my script but when I try to initialize I am told it is out of scope. How do I access it in the same script and how do I access it from another script?

using UnityEngine;
using System.Collections;
public class GameLoop : MonoBehaviour 
{
 public int[,] HOME = new int[4, 1]; //[Resource,Capacity]
    void Start ()
    {
       HOME[0, 0] = 0; //Resource0 stored
       HOME[0, 1] = 100; //Resource0 storage capacity
    }
}

Share this post


Link to post
Share on other sites
Accessing it in the same script should work like you have written.

However, this line will give you an IndexOutOfRangeException:

HOME[0, 1] = 100;

...because [4,1] means "4 x 1", which means you have [0 to 3, 0] as the valid range you can plug in.

public int[,] HOME = new int[4, 1];



Accessing your HOME variable in another script requires your other script to get access to the GameLoop instance somehow. In Unity you have several options. If the other script is attached to the same GameObject, you can say:

public class OtherClass : MonoBehaviour
{
   void Start()
   {
      var gameloop = GetComponent<GameLoop>();
      if (gameloop != null)
      {
          gameloop.HOME[0,0] = 0; // or whatever.
      }
   }
}
If your component is on a different GameObject, there are a variety of other ways to handle it. You could store a static reference to your GameLoop:

public class GameLoop : MonoBehaviour
{
    public static GameLoop Instance;
    
    void Awake()
    {
        Instance = this;
    }
}
and then your other script would change to this:

public class OtherClass : MonoBehaviour
{
   void Start()
   {
      var gameloop = GameLoop.Instance;
      if (gameloop != null)
      {
          gameloop.HOME[0,0] = 0; // or whatever.
      }
   }
}
or you could do this:

public class OtherClass : MonoBehaviour
{
   void Start()
   {
      var gameloop = GameObject.FindObjectOfType<GameLoop>();
      if (gameloop != null)
      {
          gameloop.HOME[0,0] = 0; // or whatever.
      }
   }
}


I would also suggest not using all-capital variable names. "HOME" should be "Home" instead, since it's public. If it was private, it should be "home".

Share this post


Link to post
Share on other sites

public int[,] HOME = new int[4, 1]; //[Resource,Capacity]

 

You are declaring a 2D array with 4*1 entries,

which looks like this:

0 0 0 0

Now what your access code is doing is accessing it like that:

0 // 0/0
0 // 0/1

I'm not entirely sure what you are trying to do here, but you eigther need to need to increase the vertical size of the array, or change something about your approach.

 

EDIT: Ninja'd, damn smile.png

Edited by Juliean

Share this post


Link to post
Share on other sites

Okay so I think I’m completely misunderstanding how multidimensional arrays work in C#. I’m coming from Basic where I would use an array to catalog information. Home[0,] would be like my container and every dimension after would relate to the first dimension. The declaration Home[1,1] would mean (0,0), (0,1), (1,0), and (1,1) would all be separate pieces of information.

 

So in C# Home[1,1] would be the same as Home[1] because it means Home[1x1], giving me Home[0] and Home[1] to hold information?

 

Home[2,2] would give me Home[0-4], Home[2,2,2] would give me Home[0-8]?

Share this post


Link to post
Share on other sites

So in C# Home[1,1] would be the same as Home[1] because it means Home[1x1], giving me Home[0] and Home[1] to hold information?



Home[2,2] would give me Home[0-4], Home[2,2,2] would give me Home[0-8]?
 

 

Not quite. Home[X,Y] are coordinates into the array. Both start at 0. So 1,1 gives you 1 into the array horizontally, and 1 vertically. The formula for the linear array key is actually:

Y * width + X

Since multidimensional arrays are actually ordered line by line:

   1 2 3 4 -> // 0/0 - 3/0
-> 5 6 7 8    // 0/1 - 3/1

So you can access this whole array in the range of Home[0,0] to Home[3,1].

Edited by Juliean

Share this post


Link to post
Share on other sites

Not quite. Home[X,Y] are coordinates into the array. Both start at 0. So 1,1 gives you 1 into the array horizontally, and 1 vertically. The formula for the linear array key is actually:

Y * width + X

Since multidimensional arrays are actually ordered line by line:

   1 2 3 4 -> // 0/0 - 3/0
-> 5 6 7 8    // 0/1 - 3/1

So you can access this whole array in the range of Home[0,0] to Home[3,1].

 

 

Had me at coordinates but then lost me again, sorry.

yy

xx

Home[1,1] should give me 4 right?

1

0 1

But how do I write it?

My understanding of this was…

Home[0,0] would be the 0

Home[0,1] would be the 1 above 0

Home[1,0] would be the 1 after the 0.

Home[1,1] would be above the 1.

 

Again I'm sorry it hasent clicked for me yet.

Share this post


Link to post
Share on other sites

Had me at coordinates but then lost me again, sorry.

yy

xx

Home[1,1] should give me 4 right?

1

0 1

But how do I write it?

My understanding of this was…

Home[0,0] would be the 0

Home[0,1] would be the 1 above 0

Home[1,0] would be the 1 after the 0.

Home[1,1] would be above the 1.

 

Again, not quite. 1,1 gives you 6 - it accesses 2 elements in horizontally, and then 2 vertically.

 

Maybe this should make it clear:

    0 1 2 3 X

0   1 2 3 4 
1   5 6 7 8
2   9 1 2 3
3   4 5 6 7

Y

Any combination of X/Y from this table for an square 2d array will give you the element in that row/colum, 0/2 will give you 9 e.g. This works for every form of 2D-array, just put first access index as "X", second as "Y", and fill this table due to width/height.

 

Aside from that, I strongly second phil_t's suggestion.

Edited by Juliean

Share this post


Link to post
Share on other sites

I have to agree with phil_t about changing this to a different type of data structure that will provide you a little more flexibility in your game. 

 

Array's suffer from not being able to expand them very easily because their one large contiguous segment of memory.  This provides for very fast access to your data elements but at the cost of searching for something will be cost you lots of cpu cycles.  Granted only have an array 4x4 isn't a large amount of data so the extra time wouldn't cost you much.  If you have to expand the array though as it gets larger the time will exponentially increase for finding elements in the array.

Share this post


Link to post
Share on other sites

Adehm; you're misunderstanding how indices work, in contrast to how array allocation works.

 

public int[,] HOME = new int[4, 1];

 

This gives you an array of 1 by 4 cells. It's your choice to call those columns and rows or rows and columns.

 

But arrays are what is called "0-indexed." A one-dimensional array of size 5 (say, int[] list = new int[5]) has valid indexes 0 and 1 and 2 and 3 and 4; five total cells, starting at cell number zero. Similarly, a two-dimensional array of size 4,1 has valid indexes 0,0 and 1,0 and 2,0 and 3,0... and that's it. To store two "fields" per "row", you want new int[4,2], and index them at R,0 and R,1.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this  

  • Announcements

  • Forum Statistics

    • Total Topics
      628336
    • Total Posts
      2982158
  • Similar Content

    • By Afambus
      Hello,
      I have a full experienced team that looking for a composer and another 3d designer, im expecting as much from you there are other people in this server that can help you we have a determined team, we have done many things in our game there is more information in the discord about everyone and there skills there region and about the game, if you join the discord pm asap
      https://discord.gg/b2teN3m
    • By BAG Labs
      Mobile SoS

      Platform: Android
      Genre: Board
      Link: Google Play
       
      This games sharpen memory and test your strategies to place S-O-S pattern within time limit and serve 3 difficulties as Easy, Normal, and Hard.

      Goals of the game is to put S-O-S words in patterns (Horizontal, Vertical, and Diagonal) alternately with enemy.
       
      Features:
      Single Player Multiplayer Achievements Leaderboards  
       
      Screenshot:

       

       

       
      Link: Google Play
       
      Please help us improve this game with review
    • By abarnes
      Hello!
      I am a game development student in my second year of a three year program and I would like to start building my portfolio. I was thinking of creating some games to show what I can do to potential employers since I wont have any work related experience when I graduate. But as I'm sure you all know there are tons of ways to approach developing/designing a game and I'm curious if anyone had any insight as to any "standards" that come with this? Is it okay to use game engines like Unity, Unreal, Game Maker etc? Or would it be better to make a game from scratch to better show case your skills? Any and all advice will be greatly appreciated!
    • By Hilster
      Hello 2D Artists,
      I've started making a 2D Puzzle Adventure game for mobile and I'm looking for someone who would want in on creating assets for the game. The core of the programming is pretty much complete, you can walk within the grid laid out and push boxes, when there is an object on top of a pressure pad it will activate the linked objects or if there is one object with multiple linked pressure pads it requires you to activate all points for the object to become active. 

      The level iteration for the game is quick and simple, a Photoshop file that is made of individual pixels that represents objects is put into the game and it creates the level out of those pixels with the assigned objects.
      The objects that need sprites created so far is the character, box, pressure pad, door, trap door, the walls, the stairs and the tiled background.
      I intend to add more objects so the amount I'd like to add will be extended.
      My motivations for posting here is to have something that looks nice to be able to display on my portfolio, so if you're looking for a working game that you can place your art into and improve the look of your portfolio then we're in business.
      Please reply with a few past examples of your art below and I'll be in touch!
    • By thefollower
      Hi
      I have set up my TcpClient to connect to my server and that works fine. But i am a bit confused how i read messages from the network stream with it continuously running via async, without ever closing the connection ?
      My TcpClient Manager class has:
       
      public async Task<bool> Connect(string address, int port) { try { await _tcpClient.ConnectAsync(address, port); IsConnected = true; return true; } catch(Exception e) { Debug.Log(e); return false; } } public async Task<int> Read(byte[] readBuffer) { if (!IsConnected) return -1; using (var networkStream = _tcpClient.GetStream()) { try { var bytesRead = await networkStream.ReadAsync(readBuffer, 0, readBuffer.Length); return bytesRead; } catch (Exception e) { Debug.Log(e); IsConnected = false; return -1; } } }  
      So i thought to just run a co-routine and call Read constantly to get the most recent message, but that doesn't make much sense to me since a co-routine would be blocked with the await. How is this actually done? The MS Docs don't have very good Async examples with the TcpClient class so i don't know fully get how to keep calling Read correctly.
  • Popular Now