• 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 Topthink · Jan 01, 2017 at 03:19 AM · listaddaddcomponent

How to add to Generic List ?

I'm trying to populate my list but I get the WARNING message


..... "You are trying to create a MonoBehaviour using the "new" keyword. This is not allowed. MonoBehaviors can only be added using AddComponent(). " .....

I get different warnings if I don't inherit from MonoBehavior but my impression is that I need to inherit. I can't find any full documentation on how to "AddComponent". Bummer. Been working on this all day.

 public class Runner : MonoBehaviour
 {
     public float speed { get; set; }
     public float acceleration { get; set; }
 
     public Runner (float s, float a)
     {
         speed = s;
         acceleration = a;
     }
     List<Runner> runners = new List<Runner>();
 
     void Awake ()
     {
         runners.Add(new Runner(5,5));  // <<<<<  This is culprit <<<<<<
     }
 
 
 
 
 

Comment
Add comment · Show 4
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 Topthink · Jan 01, 2017 at 03:21 AM 0
Share

The message is not an outright error...it's simply a warning. But it seems as though it will have negative effects down the line.

How the heck can I add to my list?

avatar image Topthink · Jan 01, 2017 at 03:25 AM 0
Share

$$anonymous$$y objective is to use the list to create class items (speed and acceleration) that I can use to insert into a Nav$$anonymous$$eshAgent.

avatar image RobAnthem · Jan 02, 2017 at 07:36 PM 0
Share

About your Nav$$anonymous$$esh issue, this worked 100% in testing.

 Nav$$anonymous$$eshAgent navAgent = new Nav$$anonymous$$eshAgent();
 navAgent.speed = FindObjectOfType<otherScript>().navAgent.speed;
avatar image Topthink · Jan 02, 2017 at 08:12 PM 0
Share

Thanks Rob. $$anonymous$$y pool/universe of Runners don't have a Nav$$anonymous$$eshAgent yet. There is no need to add one to that pool...that pool/universe has only the speed and acceleration data stored in it...I'm using my List to store that class data.

The only ones that have the Nav$$anonymous$$eshAgent are the four or five that are selected to be in the race...those four/five selected to race are placed in a small array to which I add the Nav$$anonymous$$eshAgent. Right now, my Runner/Racers are just spheres that compete over a short race course.

4 Replies

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

Answer by TBruce · Jan 01, 2017 at 04:03 AM

Happy New Year @Topthink,

You basically have to ways to approach this

  1. Make your runner a prefab

  2. Create a generic class or struct for your runner data

Method 1 - RunnerManager.cs & Runner.cs

 using UnityEngine;
 using System.Collections;
 using System.Collections.Generic;
 using System;
 
 [System.Serializable]
 public class RunnerManager : MonoBehaviour
 {
     public Runner runnerPrefab;
     
     public int numRunnersToCreate = 5;
 
     [SerializeField]
     public List<Runner> runners = new List<Runner>();
 
     void Start ()
     {
         if (runnerPrefab != null)
         {
             for (int i = 0; i < numRunnersToCreate; i++)
             {
                 Runner runner = Instantiate(runnerPrefab);
                 runners.Add(runner);
             }
         }
     }
 }
 
 using UnityEngine;
 using System.Collections;
 
 [System.Serializable]
 public class Runner : MonoBehaviour
 {
     public float speed;
     public float acceleration;
 
     public Runner ()
     {
         speed = 5;
         acceleration = 5;
     }
 }

Method 2 - RunnerManager.cs & Runner.cs

 using UnityEngine;
 using System.Collections;
 using System.Collections.Generic;
 
 [System.Serializable]
 public class RunnerManager : MonoBehaviour
 {
     public int numRunnersToCreate = 5;
 
     [SerializeField]
     public List<Runner> runners = new List<Runner>();
 
     void Start ()
     {
         for (int i = 0; i < numRunnersToCreate; i++)
         {
             runners.Add(new Runner(5,5));
         }
     }
 }
 
 using UnityEngine;
 using System.Collections;
 
 [System.Serializable]
 public class Runner
 {
     public float speed;
     public float acceleration;
 
     public Runner (float s, float a)
     {
         speed = s;
         acceleration = a;
     }
 }

Comment
Add comment · Show 7 · 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 Topthink · Jan 01, 2017 at 06:02 PM 0
Share

Wow. Quite a response!!! Thank you so much for taking the time to put that up for me. I'm going to start looking at it immediately.

avatar image Topthink · Jan 01, 2017 at 06:15 PM 0
Share

Happy new year to you too, by the way.

I'm looking at your stuff now. I'm going to write a program to do it both ways. This is really an important topic for me because I have two programs I'm writing that will need this so I want to make sure I understand it and can choose the most effective way to do it.

Plus, I'm an older retired guy and it takes me a bit longer to grasp some of this stuff than you younger faster wiz guys.

Thanks again, you are incredibly kind to make this sort of effort to help me and I really appreciate it. I'll be going over your material all day.

avatar image TBruce Topthink · Jan 01, 2017 at 08:49 PM 0
Share

I should have included these demo packages in my original answer

  1. $$anonymous$$ethod 1

  2. $$anonymous$$ethod 2

Note: $$anonymous$$ethod 2 is not compatible with method 1 because method 2 requires a prefab and the Runner class is a $$anonymous$$onoBehavior class not a generic class.

avatar image Topthink TBruce · Jan 01, 2017 at 09:04 PM 0
Share

Thanks again. I'm working on developing $$anonymous$$i-programs to test and learn what you posted for me. It always takes longer than I expect...I'm struggling right now with my GUI displays, LOL...right when I thought I had GUI stuff mastered.

avatar image Topthink · Jan 02, 2017 at 04:38 AM 0
Share

I forgot I had people co$$anonymous$$g over for New Years festivities. I didn't get much of a chance to work on this today. I will need to continue on this tomorrow.

Best wishes to all.

avatar image Topthink · Jan 02, 2017 at 05:06 PM 0
Share

It's 9:00 California time and I'm just getting started on this. I'll be looking at it all day probably. I'm very happy that you guys took the time to help me and I'm still working on writing the program both ways so I can make an effective decision.

avatar image Topthink · Jan 02, 2017 at 07:31 PM 0
Share

I'm pretty sure I can create my class/list...I'm successfully printing that out on a GUI and it matches perfectly with my Runner$$anonymous$$anager script so it all seems to be working.

HOWEVER...

I'm having a hard time figuring out how to change the Nav$$anonymous$$eshAgent speed (acceleration, etc) from a different script. $$anonymous$$y plan was to create the entire universe/pool in one script and then randomly select the competitors from another script.

I can display the entire pool/universe in a OnGUI from any script anywhere and it displays accurately...but I can't seem to assign the values to my Nav$$anonymous$$eshAgents from the other scripts.

I'm still researching how to do this.

avatar image
0

Answer by RobAnthem · Jan 01, 2017 at 03:40 AM

From what I've experienced, you simply need to create an empty GameObject that will exist in your scenes for you to add the script to, now I haven't 100% tested it, but from the tests I ran, it seems to make little to no difference as to whether the script sits on a GameObject or if it is just in the code, either way it must be in the RAM and as such, will take up the space it takes up. MonoBehaviour gives nice bonuses to how you can use scripts, but the downside is IT DERIVES from GameObject, so it MUST be placed on a GameObject. To do this you can simply write this.

 FindObjectOfType<RunnerObject>().gameObject.AddComponent<Runner>();

Or whatever script is attached to whatever usable object you can find and use.

so runners.Add(new Runner(5,5)); should be

 runners.Add(FindObjectOfType<RunnerObject>().gameObject.AddComponent<Runner>());
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 Topthink · Jan 01, 2017 at 03:54 AM 0
Share

I'm going to look at your answer right now and see if I can get it to work. Thanks for taking the time to help me.

avatar image Topthink · Jan 01, 2017 at 04:16 AM 0
Share

Hmmmm.

I tried it three times and Unity crashed all three times and took my terrain and some other items along with it.

I'm tired, been at it all day. I'll shut everything down and try it again tomorrow.

avatar image
0

Answer by salex100m · Jan 02, 2017 at 05:36 PM

A class that instantiates a list of itself and holds that list internally seems like incest to me... haha. Honestly don't know if it's good programming practice or not, but just seems weird. Probably breaks some golden rules of OOP.

Here's what I would do: 1) create your Runner class to hold all your variables (speed/accl/etc). 2) somewhere else (maybe on your navemesh or some other gameobject in the scene, or even your main thread gameobject if you have one: instantiate your List runners and then add to it there as runners are created somewhere else.

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 Topthink · Jan 02, 2017 at 07:22 PM 0
Share

I need to create a universe/pool of Runners, say 25, and I want to store that information in a list. And then from that 25 I want to select 4 or 5 or so to compete in a series of races. (The universe/pool will change over time and the number of racers will change from race to race...the numbers may end up being quite different, I'm just using those as examples here.)

I'm using Nav$$anonymous$$esh and Nav$$anonymous$$eshAgents because they need to find their way over a simple course...and that fits the need perfectly.

I'd like to use Class/List because it's really flexible in adding/deleting from the universe/pool without having to mess with arrays.

At least in my $$anonymous$$d, I'm trying to create what you describe there in your second paragraph. $$anonymous$$aybe I'm not conveying that in a clear manner.

I've accomplished this already in C# (outside Unity) with multi-dimensional arrays. I just don't think they will be flexible enough going forward, though. Thus the need for a list/class structure.

I appreciate your input and I'll continue to work on this.

avatar image Topthink · Jan 02, 2017 at 07:25 PM 0
Share

$$anonymous$$y struggle here is totally with the class/list structure/syntax inside the Unity Engine. I'm pulling my hair out (what little I have left) trying to figure this out.

I'm having a heckuva time trying to figure out how to extract the data from one script and place it into the Nav$$anonymous$$eshAgent in another script.

avatar image
0

Answer by Topthink · Jan 02, 2017 at 09:41 PM

I still have outstanding questions here but the questions have evolved well beyond the original inquiry so I accepted an answer above and I'll repost the new question in a different thread.

Basically, I'm able to add items to my list at will and that concern has been addressed.

Thanks everyone for your help.

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.

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

62 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 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 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

A node in a childnode? 1 Answer

add items to a list in multiples 0 Answers

Keep adding targets to a list 2 Answers

C# Adding Multiple Elements to a List on One Line 5 Answers

How do I add a float variable into a list ? 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