Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • 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
1
Question by vib5252 · Sep 21, 2011 at 03:26 AM · c#2dgameobjectarray

2D array of GameObjects C#

Hello Guys,

I am trying to load prefabs (that reside in the resources folder) in a 2d array. The problem lies in this line:

pieces[i][j] = (GameObject) Instantiate (gems[i], new Vector2(i,j), Quaternion.identity);

Here is the entire code: using UnityEngine; using System.Collections;

public class Test : MonoBehaviour {

 public int spawn;
 public int rows;
 public int cols;
 public GameObject gemObject;
 public GameObject [][] pieces;
 public Object [] gems;
 
 
 // Use this for initialization
 void Start () {
     
     //Initializing variables
     rows = 10;
     cols = 10;
     spawn = 15;
     pieces = new GameObject[rows][];
 
     //load's gems from the resources Gem folder to this object array
     gems = Resources.LoadAll("Gems", typeof(GameObject));             
     
     for (int i = 0; i < gems.Length; i++)
         Debug.Log("gems #" + i + "is: " + gems[i].name);
     
     for (int i=0; i < rows; i++) {
         for (int j=0; j<cols; j++){
             pieces[i][j] = (GameObject) Instantiate (gems[i], new Vector2(i,j), Quaternion.identity);
         }
     }
 }

}//end class

The error I get is: "NullReferenceException: Object reference not set to an instance of an object"

Would appreciate any feedback. Thanks

Comment
Add comment · Show 3
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 IMTRIGGERHAPPY9 · Sep 27, 2011 at 11:32 PM 1
Share

Anybody know how to do the same thing in JavaScript?

avatar image aldonaletto IMTRIGGERHAPPY9 · Sep 28, 2011 at 12:18 AM 2
Share

I've not tested this, but at least it compiled ok:

public var spawn = 15; public var rows = 10; public var cols = 10; public var gemObject: GameObject; public var pieces: GameObject [,]; public var gems: Object [];

function Start () { //Initializing variables pieces = new GameObject[rows, cols];

 //load's gems from the resources Gem folder to this object array
 gems = Resources.LoadAll("Gems", GameObject);        

 for (i = 0; i < gems.Length; i++)
     Debug.Log("gems #" + i + "is: " + gems[i].name);

 for (i = 0; i < rows; i++) {
     for (j = 0; j < cols; j++){
         pieces[i,j] = Instantiate (gems[i], Vector2(i,j), Quaternion.identity);
     }
 }

}

avatar image IMTRIGGERHAPPY9 IMTRIGGERHAPPY9 · Sep 28, 2011 at 03:26 AM 0
Share

Thank you so much! after a months work i have finally gotten the code to work exactly how i want it. now i can move on to bigger and better things! i learned a ton about unity through this one code though!

2 Replies

· Add your reply
  • Sort: 
avatar image
1

Answer by vib5252 · Sep 21, 2011 at 04:20 PM

Thanks. I figured it out in C#. I wasn't dynamically creating the rows and didn't declare the 2d array properly.

  1. Declare 2D array

  2. (Dynamically) Initialize the 2D array

  3. In the for loop (Dynamically) initialize the row and populate

1. public GameObject [][] pieces;

2. pieces = new GameObject[rows][];

3.

     for (int i=0; i < rows; i++) {
         pieces[i] = new GameObject[rows];
         for (int j=0; j<cols; j++){
             pieces[i][j] = (GameObject) Instantiate (gems[i], new Vector2(i,j), Quaternion.identity);
             
         }
     }
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
avatar image
0

Answer by jahroy · Sep 21, 2011 at 04:05 AM

The line of code that's causing problems appears to assume that you can dynamically resize a builtin array.

That is not allowed.

You never declare the size of the array before you start trying to populate it.

I'm sure there are many options, but I can think of three quickly:

  1. Use dynamic arrays to fill the arrays with data, then convert them to builtin arrays afterwards.
  2. Declare the size of your two-dimensional, builtin array before you try to fill it with data. I don't know how to do this. I think I tried for about two seconds one day then decided there were WAY better ways to accomplish my goal.
  3. Use a builtin array of dymanic arrays (see code below) to make it nice and simple.

You can read the documentation that describes the difference between builtin arrays and "javascript style" arrays here.

Here's some example code that uses a builtin array of dynamic arrays.

function populateArrayOfArrays () { var rows = 10; var cols = 20;

 /* declare a builtin array of 10 dynamic arrays */

 var twoDimArray : Array [] = new Array [rows]; 

 for ( var i = 0; i &lt; rows; i ++ ) {

     /* create an new, empty array that can be resized */

     var temporaryDynamicArray = new Array();

     /* populate the temporary array */

     for ( var j = 0; j &lt; cols; j ++ ) {
         temporaryDynamicArray.Push(generateObject(i, j));
     }

     twoDimArray[i] = temporaryDynamicArray;
 }


 /* test to see if it worked */

 for ( var r = 0; r &lt; rows; r ++ ) {
     for ( var theItem : String in twoDimArray[r] ) {
         Debug.Log("Here's my story: " + theItem);
     }
 }

}

function generateObject ( theI, theJ ) { return "String: (" + theI + ", " + theJ + ")"; }

In my example I use an array of String arrays (rather than an array of GameObject arrays) but it shouldn't matter.

You can just replace generateObject(i, j) with a function (or code) that instantiates a GameObject.

The above example works for me:

(Image deleted)

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.

Follow this Question

Answers Answers and Comments

5 People are following this question.

avatar image avatar image avatar image avatar image avatar image

Related Questions

Call Methods from inactive GameObjects 1 Answer

Itween gradual jump 2d 1 Answer

How to copy part of an array 2 Answers

How can I make this GameObjects array remain permanent when i activate? 1 Answer

How to Instantiate Objects at specific Spawn Points without overlapping? 0 Answers


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