Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 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
0
Question by GarrettM · Apr 10, 2014 at 04:16 PM · instantiatearrayspawnarraysspawning

How Do I Add An Instantiated Object To An Array?

I'm working on a game where cubes spawn randomly from 5 different spawn points, and I need to know how to get them into an array when spawned so that I can keep track of where the cubes spawned, that way I can check later to see if cubes of a certain color are in a row (bonus points if you can help me figure that out as well). The cubes don't currently have colors assigned to them, but they well when this is done. Right now I'm just trying to get them into the array so I can keep track of them.

Here's what I've got so far:

 #pragma strict
 var timer : float = 0.0;
 var spawning : boolean = false;
 var prefab : Rigidbody;
 var spawn1 : Transform;
 var spawn2 : Transform;
 var spawn3 : Transform;
 var spawn4 : Transform;
 var spawn5 : Transform;
 var cubes : GameObject[];
  
 function Update () {
  //check if spawning at the moment, if not add to timer
      if(!spawning){
           timer += Time.deltaTime;
      }
  //when timer reaches 2 seconds, call Spawn function
      if(timer >= 2){
           Spawn();
      }
 }
  
 function Spawn(){
      //set spawning to true, to stop timer counting in the Update function
      spawning = true;
      //reset the timer to 0 so process can start over
      timer = 0;
      
      //select a random number, inside a maths function absolute command to ensure it is a whole number
      var randomPick : int = Mathf.Abs(Random.Range(1,6));
      
      //create a location 'Transform' type variable to store one of 3 possible locations declared at top of script
      var location : Transform;
      
      //check what randomPick is, and select one of the 3 locations, based on that number
      if(randomPick == 1){
           location = spawn1;
           Debug.Log("Chose pos 1");
      }
      else if(randomPick == 2){
           location = spawn2;
           Debug.Log("Chose pos 2");
      }
      else if(randomPick == 3){
           location = spawn3;
           Debug.Log("Chose pos 3");
      }
       else if(randomPick == 4){
           location = spawn4;
           Debug.Log("Chose pos 4");
      }
       else if(randomPick == 5){
           location = spawn5;
           Debug.Log("Chose pos 5");
      }
      
      //create the object at point of the location variable
      var thingToMake : Rigidbody = Instantiate(prefab, location.position, location.rotation);
      // thingToMake.AddForce(Vector3(0,0,100));
      
      //halt script for 1 second before returning to the start of the process
      yield WaitForSeconds(1);
      //set spawning back to false so timer may start again
      spawning = false;
 }
Comment
Add comment
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

3 Replies

· Add your reply
  • Sort: 
avatar image
-1

Answer by cliffbrown · Apr 10, 2014 at 06:47 PM

Adding to a UnityScript array is as simple as:

 cubes.push(OBJECT);
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 robertbu · Apr 10, 2014 at 06:48 PM 0
Share

@cliffbrown - this will not work with built-in arrays like the OP has in his code. And you should avoid the Array class...it is slow and untyped.

avatar image
0

Answer by robertbu · Apr 10, 2014 at 06:50 PM

Use .NET generic lists. Lots of posts on Lists. Here is a link that includes some information on many of the collection types used in Unity:

http://wiki.unity3d.com/index.php?title=Which_Kind_Of_Array_Or_Collection_Should_I_Use%3F

At the top of the file you will need:

 import System.Collections.Generic;

Then you will declare your variable:

 var cubes : List.<GameObject> = new List.<GameObject>();

Then you can add them to the list with:

 myList.Add(thingToMake.gameObject);

Note if you tag all of your cubes, you can use GameObject.FindGameObjectsWithTag() to get a current array of game objects with that tag. It is a bit less efficient than maintaining your own list, but it is fast enough to use every frame for any reasonable number of cubes.

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 GarrettM · Apr 11, 2014 at 12:04 AM

Thanks for the help everyone! I actually ended up doing it this way:

 #pragma strict
 var timer : float = 0.0;
 var spawning : boolean = false;
 var prefab : GameObject;
 var spawn1 : Transform;
 var spawn2 : Transform;
 var spawn3 : Transform;
 var spawn4 : Transform;
 var spawn5 : Transform;
 //var cubes : GameObject[];
 var board : GameObject[, ];
 var boxColor : Color[];
 private var count : int = 0;
 private var color : int;
 function Start()
 {
     //cubes = new GameObject[40];//[max no of cubes]
     board = new GameObject[5,8];//[x,y]
     count =0;//just making sure this starts at zero
 }
 function Update () {
  //check if spawning at the moment, if not add to timer
      if(!spawning){
           timer += Time.deltaTime;
      }
  //when timer reaches 2 seconds, call Spawn function
      if(timer >= 2){
           Spawn();
      }
 }
  
 function Spawn(){
      //set spawning to true, to stop timer counting in the Update function
      spawning = true;
      //reset the timer to 0 so process can start over
      timer = 0;
      
      //select a random number, inside a maths function absolute command to ensure it is a whole number
      var randomPick : int = Mathf.Abs(Random.Range(1,6));
      
      //create a location 'Transform' type variable to store one of 3 possible locations declared at top of script
      var location : Transform;
      
      //check what randomPick is, and select one of the 3 locations, based on that number
      if(randomPick == 1){
           location = spawn1;
           Debug.Log("Chose pos 1");
      }
      else if(randomPick == 2){
           location = spawn2;
           Debug.Log("Chose pos 2");
      }
      else if(randomPick == 3){
           location = spawn3;
           Debug.Log("Chose pos 3");
      }
       else if(randomPick == 4){
           location = spawn4;
           Debug.Log("Chose pos 4");
      }
       else if(randomPick == 5){
           location = spawn5;
           Debug.Log("Chose pos 5");
      }
      
      //create the object at point of the location variable
      //thingToMake is just a temporary variable to hold our cube 
      var thingToMake : GameObject = Instantiate(prefab, location.position, location.rotation);
      thingToMake.renderer.material.color = boxColor[color];
      color = Mathf.Abs(Random.Range(0, boxColor.Length));
      //put elements in arrays
      //store cubes in "max" and this will allow us to run checks against their color or any other property
      //cubes[count] = thingToMake;
      for(var i= 0; i < 8; i++)
      {
          if(board[randomPick-1,i]==null)
          {
              //add the cube to our "game board" to keep track of where it is, this is our 2D array
              board[(randomPick-1),i] = thingToMake;
              break;
         }
      }
      if(board[0,7] != null || board [1,7] != null || board [2,7] != null || board [3,7] != null || board[4,7] != null )
          Application.LoadLevel("LoseScene");
      //halt script for 1 second before returning to the start of the process
      yield WaitForSeconds(1);
      //set spawning back to false so timer may start again
      spawning = false;
      //increment count
      count++;
 }
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

22 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 avatar image

Related Questions

Cannot find the length of an array 3 Answers

Instantiate 1 at a time at each transform in array 1 Answer

Having Trouble with Instantiating an object on an axis 2 Answers

Prefabs instantiated from an array are keeping their public int value 1 Answer

How do i prevent an object instantiating another object straight away 2 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