• Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by ToeTag · Nov 21, 2013 at 07:05 PM · c#arrays

Assigning a gameobject to an array

I am new to Unity, and programming, and have been searching and reading about arrays but cannot seem to find an answer to my questions.

For me to better understand an array. I thought a simple TicTacToe game would help. So far I have created only a single dimension with 3 cubes that are under an emptyObject as children and taged as "Player". Obviously their will be a total of 9 in a 2 dimension array. The human players will use the mouse to click on a cube to change the texture to X or O.

Now for the question: How do you assign the cubes name cube1, cube2, cube3 (which is what they are called in hierarchy) to the array. This is what I have so far that works but does not really identify which cube is which?

 void blockArray()
     {
         cubeArray = new string[3];
         cubeArray[0] = GameObject.FindWithTag("Player").tag;
         cubeArray[1] = GameObject.FindWithTag("Player").tag;
         cubeArray[2] = GameObject.FindWithTag("Player").tag;
         print (cubeArray[0]);
         print (cubeArray[1]);
         print (cubeArray[2]);
     }

the outcome of the print statement is just player 3 times. Instead of cube1, cube2, cube3.

Comment
Add comment · Show 7
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image ToeTag · Nov 22, 2013 at 12:23 AM 0
Share

Follow-up question: The first Idea with using the inspector is working however, I cannot see how to change it into a multidimensional array.

 public GameObject[,] cubes; //just putting the [,] should make it multidimensional I thought.

the second idea produces a unexpected result, but is $$anonymous$$ching me about the array. When I try to print it to the Console I get:

Null, cube1, and cube2. I was expecting Cube1, Cube2, Cube3. the code is the same from above except I added the print line.

     private void blockArray()
     {
 
         GameObject parentGo = GameObject.FindWithTag("Player");
         cubeArray = new GameObject[parentGo.transform.childCount];
         for(int i = 0; i < parentGo.transform.childCount; ++i)
         {
             cubeArray[i] = GameObject.Find("Cube" + i);
             print(cubeArray[i]);
         }
avatar image Key_Less ToeTag · Nov 22, 2013 at 01:14 AM 0
Share

If you want to simulate a multidimensional array that is assignable through the inspector, you could try this...

 [Serializable]
 public class $$anonymous$$yCubeArray
 {
     public GameObject[] cubes;
 }
 public $$anonymous$$yCubeArray[] Rows;

It will look like this in the inspector...

alt text

And you could access the cubes like this...

 for (var i = 0; i < Rows.Length; ++i)
 {
     for (var j = 0; j < Rows[i].cubes.Length; ++j)
     {
         print(Rows[i].cubes[j].name);
     }
 }

Again, if you need the cubes in a multidimensional array and don't want to search for them at runtime, you could do it this way so that you can assign them through the inspector. Though I'm sure there are plenty other methods to achieve the same thing that are better than this.

inspector.png (3.1 kB)
avatar image Key_Less ToeTag · Nov 22, 2013 at 01:25 AM 0
Share

Just in case, in order to use the [Serializable] attribute, you'll need to include the using System; statement in global space above the class, or implement it explicitly ([System.Serializable]).

avatar image ToeTag ToeTag · Nov 22, 2013 at 02:04 AM 0
Share

$$anonymous$$ey_Less, thanks for the reply. I'm not getting the same thing as you have. Here is my entire code based upon your suggestions. Basically created a new cs script for this:

 using UnityEngine;
 using System.Collections;
 using System;
 
 
 [Serializable]
 public class $$anonymous$$yCubeArray : $$anonymous$$onoBehaviour 
 {
     public GameObject[] cubes;
     // Use this for initialization
 
     public $$anonymous$$yCubeArray[]Rows;
 }
 

ScreenShot

notice that the Cubes and Rows appear to be separate lists. (I hope this looks right. I see no preview for this reply).

inspectorpic.png (11.7 kB)
avatar image Key_Less · Nov 22, 2013 at 02:44 AM 0
Share

Sorry ToeTag, I should have clarified that you can add the serializable class within the Board class itself. Try this:

 public class Board : $$anonymous$$onobehaviour
 {
     [Serializable]
     public class $$anonymous$$yCubeArray
     {
         public GameObject[] cubes;
     }
     public $$anonymous$$yCubeArray[] Rows;
 }
avatar image ToeTag · Nov 22, 2013 at 07:21 PM 0
Share

Thank you so much for the clarification. It now looks the why yours does.

I had to use [System.Serializable]. for some reason trying to add: using System.Serializable was not available. At least as the auto typing complete. I always assume if it does not pop up on the list of items that, that item is not available.

avatar image holdingjupiter · Sep 20, 2015 at 06:45 PM 0
Share

Loving this thread. I was wondering if anyone knows how to make an infinite array of arrays using this method? I was playing around with it and I can make as deep an array as repeating classes that I make, but I can't figure out the logic to make it loop infinitely deep. Using it to make a conversation tree system and I would rather not be restrained by the depth a conversation can take. Any thoughts? Thanks in advance.

4 Replies

· Add your reply
  • Sort: 
avatar image
0

Answer by Key_Less · Nov 21, 2013 at 07:18 PM

An alternative route you can experiment with would be to use a handle to each cube object. You could declare a public list of GameObjects within your class scope, attach the script to your emptyObject, and fill that list with your cubes inside of the inspector.

 // Add your cubes into this list from the Unity Inspector.
 public List<GameObject> Cubes;

This way you can index into the list and find the cube you want. Ex:

 print (Cubes[0].name); // prints: cube1
Comment
Add comment · Show 4 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image ToeTag · Nov 21, 2013 at 08:15 PM 0
Share

Thanks for the reply. Unfortunately public List Cubes; produced an error. But was on the right track.

avatar image kromenak · Nov 21, 2013 at 09:58 PM 0
Share

Just FYI, C#'s generic containers, like List, are valuable tools. You just need to add "using System.Containers.Generic" to the top of your code files to use them.

avatar image ToeTag · Nov 22, 2013 at 02:24 AM 0
Share

I just saw this, I tried to add using System.Containers.Generic but it does not seem to be available in order to add. I see using System.Collections.Generic; is this what you meant?

avatar image Key_Less · Nov 22, 2013 at 06:35 PM 0
Share

Yes, that's what he meant.

avatar image
0

Answer by ffxz7ff · Nov 21, 2013 at 07:26 PM

Well, you find three GameObjects with the tag "Player", and get their tag, which is "Player", and assign it to the array elements. Hence it prints out "Player".

As Key_Less pointed out, you could use the .name property of the game objects, which is what is shown in the hierarchy.

Comment
Add comment · Show 2 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image ffxz7ff · Nov 21, 2013 at 07:28 PM 1
Share

Also your 3 array elements will all contain the same cube, since you'll always get the first cube that's found with the tag "Player". You'll need to keep track of them when you declare them (as in storing them in a List or an Array, for example.)

avatar image ToeTag · Nov 22, 2013 at 02:31 AM 0
Share

I will be adding the additional 6 cubes once I figure out how to just do the simple array. The ultimate goal is to create a 3d style array [,,]. I am trying to take baby steps first lol.

avatar image
0

Answer by kromenak · Nov 21, 2013 at 08:02 PM

If at all possible, it is probably easier if you assign the cubes to the array in the editor instead of at runtime. Sometimes, you need to dynamically find and assign GameObjects at runtime, but it is more error-prone. I'd suggest assigning the GameObjects in the Unity inspector. You could do that like this:

 public class Board : Monobehaviour
 {
     //Shows up in the unity inspector.
     public GameObject[] cubes;
 
     private void Awake()
     {
         //TODO: Do stuff with cubes.
     }
 }

And then assign the cube GameObjects in the editor at design time.

If you really want to do populate the array at runtime, and you have uniquely named your cubes, you could also do something like this:

 private void BlockArray()
 {
     GameObject parentGO = GameObject.FindWithTag("Player");
     cubeArray = new GameObject[parentGO.transform.childCount];
     for(int i = 0; i < parentGO.transform.childCount; ++i)
     {
         cubeArray[i] = GameObject.Find("cube" + i);
     }
 }

Personally, I don't really like using methods like FindWithTag or Find if possible, since they introduce assumptions about scene structure and could compile fine but blow up at runtime (what if the tag changes? or what if the someone changes the cube names?).

Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image ToeTag · Nov 21, 2013 at 08:22 PM 0
Share

Perfect, this is what I was looking for. A way to identify each cube. public GameObject[] cubes; AS $$anonymous$$ey_Less mentioned above. I was able to add the three cubes to the list and print their names.

Thanks for everyone's help.

avatar image
0

Answer by Fornoreason1000 · Nov 22, 2013 at 07:17 PM

try using FindGameObjectsWithTag instead, since it return all the objects with the player tag, not just the first one.

 void blockArray()
         {
            cubeArray = new string[3];
            cubeArray[0] = GameObject.FindGameObjectsWithTag("Player")[0].name;
            cubeArray[1] = GameObject.FindGameObjectsWithTag("Player")[1].name;
            cubeArray[2] = GameObject.FindGameObjectsWithTag("Player")[2].name;
            print (cubeArray[0]);
            print (cubeArray[1]);
            print (cubeArray[2]);
         }

http://docs.unity3d.com/Documentation/ScriptReference/GameObject.FindGameObjectsWithTag.html

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

Follow this Question

Answers Answers and Comments

21 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Multiple Cars not working 1 Answer

Distribute terrain in zones 3 Answers

Array empties values on RunTime? 1 Answer

Array with two values per element 1 Answer

Algorithm for loading sounds 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges