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 glasstongue · May 10, 2014 at 03:39 AM · c#arrayprefabs

Examples on how to populate an array with prefabs

I am having trouble trying to add prefab objects into my array.

Here is the code I have so far:

 using UnityEngine;
 using System.Collections;
 
 public class globalObjectArray : MonoBehaviour {
 
 
     public GameObject[] myArray;
 
     // Use this for initialization
     void Start () {
 
         myArray = new GameObject[30];
 
         //add values
         myArray[0] = ???;
     
     }
 
 }

and my prefabs are kept in Assets/Prefabs/

Even just examples of arrays containing prefabs would be awesome to look at.

Thanks!

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

1 Reply

· Add your reply
  • Sort: 
avatar image
0

Answer by xortrox · May 11, 2014 at 02:40 PM

You might wanna look into Resources.LoadAll When I use it I usually name my prefabs with a prefix like

Assets/Resources/Prefabs/Weapons/(0)SomeWeapon

Assets/Resources/Prefabs/Weapons/(1)SomeOtherWeapon

The parenthesis with a number in it is to ensure that Resources.LoadAll loads the prefabs into my array in that order

Resources class uses any folder named "Resources" inside your Assets folder, it can be a sub folder as well like "Assets/Data/Resources"

Then "bind" them to an enumeration with index values like this

 public enum WeaponTypes
 {
 
     SomeWeapon = 0,
     SomeOtherWeapon = 1,
 
 }

As for loading:

 //I usually name this class "Base"
 //It also contains all my prefabs or other resources
 
 using System.Linq;//For array casting
 
 public static GameObject[] PrefabsWeapons{get; private set};
 
 void Start()
 {
 
     PrefabsWeapons = Resources.LoadAll("Prefabs/Weapons").Cast<GameObject>().ToArray();
 
     //How to access each weapon:
     Debug.Log(PrefabsWeapons[(int)WeaponTypes.SomeWeapon]);
 
 }

Comment
Add comment · Show 5 · 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 xortrox · May 11, 2014 at 02:41 PM 0
Share

Also, please do some research before posting :)

avatar image fafase · May 11, 2014 at 02:46 PM 0
Share

You can simplify your line with:

 PrefabsWeapons = Resources.LoadAll<GameObject>("Prefabs/Weapons");

The cast is in the generic and the array is actually not useful since the method returns an array

avatar image glasstongue · May 12, 2014 at 09:18 PM 0
Share

Thanks xortrox!

You just answered about 3 questions I had but didn't even ask.

One more thing - what do you think would be a good way to add labels(variables? tags?) to your objects so you can spawn groups of objects by their characteristics (say I wanted to find only objects that were orange, or only objects that are vegetables...)

avatar image fafase · May 13, 2014 at 05:33 PM 0
Share

Use an enum of those type with the containing possibilities.

Then have a method on the script to check if the defined type matches:

 public enum ColorEnum{
    Red, Blue, Green, Orange
 }
 
 public class Script:$$anonymous$$onoBehaviour{
    public ColorEnum colorEnum;
 
    public bool CheckForEnum(ColorEnum ce){
         return colorEnum == ce;
    }
 }
avatar image glasstongue · May 16, 2014 at 04:53 AM 0
Share

I got the array to build, but how are enums used to sort what goes into the array?

I sort of understand the concept of enums (like an array/boolean almost) but I have no idea how to actually implement them. Should they live in a separate script that I apply to the prefabs or should they live in the same file as the array builder and apply the values to the prefabs in another way?

Here is my current iteration:

 using UnityEngine;
 using System.Collections;
 
 public class spawn$$anonymous$$ultiObject : $$anonymous$$onoBehaviour {
 
     private Vector3 startPosition;
 
     private float newXPos = 0f;
 
     public float moveSpeed = 1f; // same as 1.0;
 
     public float moveDistance = 4f;
     
     public float timeLeftUntilSpawn = 0f;
 
     public float startTime = 0f;
 
     public float secondsBetweenSpawn = 1f;
     
     public static GameObject[] myObjects;
     
     void Start()
     {
         
         myObjects = Resources.LoadAll<GameObject>("Prefabs");
         
         //idk below
         //Debug.Log(myObjects[(int)objectList.???]);
 
         startPosition = transform.position;
 
     }
 
     void SpawnRandomObject() {
 
         //spawns item in array between position number 0 thru 49
         int whichItem = Random.Range (0, 49);
     
         //replace gameObjectSet with script that gathers preefabs from folder
         GameObject myObj = Instantiate (myObjects [whichItem]) as GameObject;
 
         myObj.transform.position = transform.position;
     }
     
     // Update is called once per frame
     void Update () {
     
         newXPos = $$anonymous$$athf.PingPong (Time.time * moveSpeed, moveDistance) - (moveDistance /2f);
 
         transform.position = new Vector3 (newXPos, startPosition.y, startPosition.z);
 
         timeLeftUntilSpawn = Time.time - startTime;
 
         if (timeLeftUntilSpawn >= secondsBetweenSpawn) {
             startTime = Time.time;
             timeLeftUntilSpawn = 0;
             //Debug.Log ("Spawn Object");
 
             SpawnRandomObject();
         
         }
     }
 }
 

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

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

How to move prefabs array in sine wave? 2 Answers

Multiple Cars not working 1 Answer

Distribute terrain in zones 3 Answers

[SOLVED] Problem with "foreach". 1 Answer

Unity event calling function gets nullreferencexception on bool 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