• 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 d112570 · Oct 16, 2013 at 05:41 PM · variableloopname

Can if loop be used to create variable names?

I would like to use my current if loop to generate names, if I have "p = 1 to 9" I would like to use the p from my current loop to generate a variable name for example planet1, planet2 etc. (planet + p = planet1)

 string[] planet1;
 string[] planet2;
 string[] planet3;
 string[] planet4;
 string[] planet5;
 string[] planet6;
 string[] planet7;
 string[] planet8;
 string[] planet9;

 if (sFolder) {  // Checks to see if there is a Satellites folder

                 var numSat = sFolder.transform.childCount;
                 satellites[0] = "" + numSat; // Adds Satellite amount at the given index
                 if (numSat != 0) for (int s = 1; s <=9; s++){
                     var sNameNo   = GameObject.Find("Galaxy" + cSystem + "/Planets/" + p + "/Satellites/" + s);
                     if (sNameNo) {
                         satelliteName = GameObject.Find("Galaxy" + cSystem + "/Planets/" + p + "/Satellites/" + s).GetComponent<Info>().Name;
                         satellites[s] = satelliteName; // Adds Satellite at the given index
                         var script = sNameNo.GetComponent<sOrbitAndRotate>();
                         if (script == null) sNameNo.AddComponent("sOrbitAndRotate");}}
 //                for (int i = 0; i < satellites.Length; i++){ print (planetName + " satellites[" + i + "] = " + satellites[i]);}
                 if (p == 1) planet1 = satellites;
                 if (p == 2) planet2 = satellites;
                 if (p == 3) planet3 = satellites;
                 if (p == 4) planet4 = satellites;
                 if (p == 5) planet5 = satellites;
                 if (p == 6) planet6 = satellites;
                 if (p == 7) planet7 = satellites;
                 if (p == 8) planet8 = satellites;
                 if (p == 9) planet9 = satellites;
                 satellites = new string[10];

As you can see its pretty much the same code, I like to save satellites to their planets before its reset. This code works fine, but its large. Imagine if I have more then 9 planets.

Id be nice if it looked something like this.

 [planet+p] = satellites;}   // or however you do this.
  satellites = new string[10];
Comment
Add comment · Show 6
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 flaviusxvii · Oct 16, 2013 at 07:02 PM 2
Share

Why on Earth do you want variables for all of these? Use arrays or lists, that's what they are there for.

avatar image d112570 · Oct 16, 2013 at 07:06 PM 0
Share

It is a variables. I only used var as a test to print before I correctly initialize it, it worked like an array. I Fixed my code, a while back.

avatar image Eric5h5 · Oct 16, 2013 at 08:25 PM 2
Share

Under no circumstances do you want to do something like this. Use arrays/dictionaries/some sort of collection. When you start using sequences of named variables, Ur Doin It Rong™.

avatar image vexe · Oct 28, 2013 at 09:29 PM 0
Share

@d112570 you still having problems? if not, have you considered ticking an answer?

avatar image Tomer-Barkan · Oct 28, 2013 at 09:32 PM 0
Share

Just use a dictionary. Ins$$anonymous$$d of using a variable directly, you can use dict[variable], and the key can be a string.

Show more comments

2 Replies

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

Answer by clunk47 · Oct 16, 2013 at 06:06 PM

I'd use Linq to create a range of numbers, then use Generic List to create a list of names from the int array.

C# Example:

 using UnityEngine;
 using System.Collections;
 using System.Collections.Generic;
 using System.Linq;
 
 public class Example : MonoBehaviour 
 {
     int[] pNum;
     List<string> pName;
     
     void Start()
     {
         pName = new List<string>();
         pNum = Enumerable.Range(1, 100).ToArray();
         foreach(int num in pNum)
             pName.Add ("Planet "+num.ToString ());
         foreach(string name in pName)
             print (name);
     }
 }
 


JS Example:

 #pragma strict
 
 import System.Collections.Generic;
 import System.Linq;
 
 private var pNum : int[] = Enumerable.Range(1, 100).ToArray();
 private var pName : List.<String> = new List.<String>();
 
 function Start()
 {
     for(var num : int in pNum)
         pName.Add("Planet "+num.ToString());
     
     for(var name : String in pName)
         print(name);
 }
Comment
Add comment · Show 16 · 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 clunk47 · Oct 16, 2013 at 06:31 PM 1
Share
 using UnityEngine;
 using System.Collections;
 
 public class Example : $$anonymous$$onoBehaviour 
 {
     string[] names;
     
     void Start()
     {
         names = new string[]{"$$anonymous$$oon", "$$anonymous$$eplar", "Earth", "Space Junk", "Sun"};
         for(int i = 0; i < names.Length; i++)
         {
             names[i] = "name "+i.ToString()+" = "+names[i];
             print (names[i]);
         }
     }
 }
 
avatar image clunk47 · Oct 16, 2013 at 06:33 PM 1
Share

If you want to create a separate list with the newly formatted names:

 using UnityEngine;
 using System.Collections;
 using System.Collections.Generic;
 
 public class Example : $$anonymous$$onoBehaviour 
 {
     string[] names;
     List<string> formattedNames = new List<string>();
     
     void Start()
     {
         names = new string[]{"$$anonymous$$oon", "$$anonymous$$eplar", "Earth", "Space Junk", "Sun"};
         for(int i = 0; i < names.Length; i++)
         {
             names[i] = "name "+i.ToString()+" = "+names[i];
             formattedNames.Add (names[i]);
         }
         
         foreach(string FName in formattedNames)
             print (FName);
     }
 }
 
avatar image flaviusxvii · Oct 16, 2013 at 07:06 PM 1
Share

@d112570 Step away from the program$$anonymous$$g for a second and describe what you are actually trying to solve. This approach of generating variables isn't something you ever want to do.

avatar image clunk47 · Oct 16, 2013 at 07:11 PM 1
Share

I did look at the top where your code is, that's why I gave you an example of how to use lists and arrays ins$$anonymous$$d of having a line of code for every single (what should be) index of an array. I agree with @flaviusxvii, please tell us in plain english, what you are trying to achieve. Example: "I have some planets tagged "yourTag" in the hierarchy, each planet has objects("satellites") as children. Each planet has a different number of children (satellites)".... Not saying this is what you're doing, but your question is very unclear.

avatar image clunk47 · Oct 16, 2013 at 07:17 PM 1
Share

Dude.

 string[] planet1;
 string[] planet2;
 string[] planet3;
 string[] planet4;
 string[] planet5;
 string[] planet6;
 string[] planet7;
 string[] planet8;
 string[] planet9;
  
 if (p == 1) planet1 = satellites;
 if (p == 2) planet2 = satellites;
 if (p == 3) planet3 = satellites;
 if (p == 4) planet4 = satellites;
 if (p == 5) planet5 = satellites;
 if (p == 6) planet6 = satellites;
 if (p == 7) planet7 = satellites;
 if (p == 8) planet8 = satellites;
 if (p == 9) planet9 = satellites;

Doesn't show us what satellites IS. What 'p' IS... Edit your question to include your full script.

Show more comments
avatar image
0

Answer by flaviusxvii · Oct 16, 2013 at 08:45 PM

Strictly speaking, yes, you can create new variables programmatically. But from what I can glean from your code this would be a particularly deranged use case.

Your organizational system makes sense, but the way you are accessing various pieces doesn't make a lot of sense.

 Galaxy

    Planet

       Satellite

Make each type if thing it's own script, and use http://docs.unity3d.com/Documentation/ScriptReference/Component.GetComponentsInChildren.html to grab the sub pieces when you need to process them.

I'm not sure what else to suggest, apart from TOTALLY ABANDONING your current line of thinking. It will not end well.

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 d112570 · Oct 16, 2013 at 08:51 PM 0
Share

yeah, I did that on my last script, I was thinking of rewriting and using list, I was hoping lists are faster then using find get components name and such. Someone kept saying find gameobject is so slow. That's why I started using lists.

avatar image flaviusxvii · Oct 16, 2013 at 09:10 PM 0
Share

Yeah.. avoid GameObject.Find if you can. But using GetComponentsInChildren is a good way to find the Satellite gameObjects that live under a Planet gameObject.

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

19 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

Related Questions

While something is reoccuring keep value the same 2 Answers

Variable declaration, what's faster/more efficient? 1 Answer

Simplify this code 3 Answers

set up identifier name on the fly 0 Answers

Comparing similarly-named variables. 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