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 hamcav · Aug 09, 2013 at 09:16 PM · instantiateprefabarrayvehicleclones

Instantiate Prefab Array with ID

Hi there, i run into a problem with instantiating. I'll try to make it short. This is my code:

//Array of GameObjects to hold the vehicles to instantiate

public GameObject[] vehicle;

//Index to give an unique id to the instantiated prefabs e.g mycar_1,mycar_2,mycar_3 etc.

private int[] index = {0};

And then i do the following

//To pick up random prefabs in the array

int rand = Random.Range(0,2);

if ( rand == 0){

//reference to my instantiated gameobject || Cast transfrom to gameobject since Instantiate() returns a transform but i want gameobject || Pick up first element in array position it where my player car is..

GameObject spawnVehicle = (GameObject)Instantiate(vehicle[0],player.transform.position+new Vector3(0,1,50), Quaternion.identity);

//Give it an unique name so my first prefab has the name MyFord which will turn into MyFord_0,MyFord_1 etc. after this line

spawnVehicle.name = vehicle[0].name + "_" + index[0];

//Increment index self explanatory

index[0] +=1;

}

This works perfect and i really achieve what i want to do but doing the same for the next GameObject in the vehicle array is ridiculous.

Now when i do the following:

if ( rand == 1){

GameObject spawnVehicle = (GameObject)Instantiate(vehicle[1],player.transform.position+new Vector3(0,1,50), Quaternion.identity);

spawnVehicle.name = vehicle[1].name + "_" + index[1];

index[1] +=1;

}

This returns not a prefab with an unique ID like it does with the first element in the Array, it just instantiates clones. The question is why? Am i missing something or what did i wrong? The big problem i dont understand is that when it works for one then shouldnt it work also for all the other vehicles in my Array??

Thanks for any help or clue.

Comment
Add comment · Show 2
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 sacredgeometry · Aug 09, 2013 at 09:56 PM 0
Share

Can you write out everything you need the script to do, the way you have attained it is a bit convoluted and if you write out the requirements I can help you understand an alternative way to tackle the problem.

avatar image hamcav · Aug 10, 2013 at 12:09 PM 0
Share

Ok, so im trying to make a little car game. The player just tilts the phone to control the car. While driving I want to instantiate other vehicles that moves towards the player and the player himself must take care not to crash. So far i managed it, and i also can instantiate the vehicles,move them etc.. The problem ive is that i cant handle it with a list or array or whatever.Becuase then outputs a NULLREFERENCE EXCEPTION. I use array because there are different types of vehicles all appearing randomly.

Or what do you suggest me to do? Write extra code for every single prefab? Doing so is ineffective.

2 Replies

· Add your reply
  • Sort: 
avatar image
1
Best Answer

Answer by sacredgeometry · Aug 10, 2013 at 12:33 PM

EDIT: I have added more robust error handelling

Here is how I would do it

public class CarSpawner : MonoBehaviour {

 public GameObject[] cars;
 private int carCounter = 0;
 private int curIndex;

 void Update () {
     
     // You can add additional tests also I would enclose the instantiation inside a method then that would probably be useful as you could then call it from other places
     
     if(cars.Length != 0 && cars[curIndex] != null){
         
         curIndex = Random.Range(0, cars.Length);

         GameObject currentCar = (GameObject)Instantiate(cars[curIndex], Vector3.zero, Quaternion.identity);        
         currentCar.name = string.Format("Whatever you want to call the car_{0}", carCounter);
         carCounter++;
     }
 }

}

The reason for the null reference exception was either because you were calling the instantiation on objects that didnt exist or because your the index you were generating with Random.Range() was out of the range. I have tried to add some defensive error handling for you.

Basically how this works is that if the array isnt empty it creates a new car object from a random one in the array(you will have to replace the position with where/however you want it to spawn)

I would recommend either tagging these cars with some sort of universal car tag or parenting them to an empty game object.This would allow you to select all of the cars and will avoid your hierarchy panel from getting inundated with spawned objects.

If you want to be able to differentiate between types of car you can do that based on the index in which they are placed ie. any car spawned at index 0 will always be the same model so if you want to tag it in a different way after instantiation you can :)

I hope that helps

Comment
Add comment · Show 3 · 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 hamcav · Aug 10, 2013 at 12:50 PM 0
Share

Nice! That solved it. Guess the issue i had was the string.Format thing. BIG THAN$$anonymous$$S :D

avatar image hamcav · Aug 10, 2013 at 01:06 PM 1
Share

it helped indeed. $$anonymous$$ost of the stuff you said im doing already. The nullreference exception was because it couldnt find the gameobject which was named for example "myvehicle(clone)". Thus it didnt give thos gameobjects the id I wanted but now it works. Thank for the additional error handling. You are welcome

avatar image sacredgeometry · Aug 10, 2013 at 01:25 PM 0
Share

Thats quite alright :)

avatar image
1

Answer by cdrandin · Aug 09, 2013 at 10:03 PM

The code is very messy, but her is what I would do to spawn objects using an array.

 // Place your prefabs or objects into the array in the inspector. 
 // You can adjust the index to add more into it.
 GameObject[] stuff; 
 
 void Start ()
 {
      for GameObject i in stuff // this is pseudocode
      {
           // spawns all objects in stuff in the center of the world.
           Instantiate(i,Vector3(0,0,0),i.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

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

15 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

Related Questions

Parenting an instantiated prefab. 1 Answer

OverlapSphere for parallel arrays 1 Answer

Instantiating an array of objects - how can I instantiate a certain prefab only once? 1 Answer

Array of prefabs 0 Answers

Instantiate is spawning too many clones 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