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 Magnomous · May 25, 2014 at 11:39 AM · c#instantiatelist

Adding instances of objects into generic list

Hello guys, I am working on simple tower defense game and I have a problem with adding GameObjects I instantiated to list. Simply, when I add instance to a list, another instance will not be instantiated...

This code is for spawning enemies and adding them to list.

 using UnityEngine;
 using System.Collections;
 
 public class GameController : MonoBehaviour {
 
     public Transform spawnPoint;
     public GameObject enemy;
     public GameObject tower;
     
     private Ray ray;
     private RaycastHit hit;
 
     // Use this for initialization
     void Start () {
 
         StartCoroutine(SpawnMinions());
     }
     
     // Update is called once per frame
     void Update () {
 
         if(Input.GetButtonDown("Fire1")) {
             ray = Camera.main.ScreenPointToRay(Input.mousePosition);
 
             if(Physics.Raycast(ray.origin, ray.direction * 100f, out hit)) {
                 
                 Instantiate(tower, hit.point + Vector3.up * 0.5f, Quaternion.identity);
             }
         }
     }
 
     IEnumerator SpawnMinions() {
         
         while(true) {
             for(int i = 0; i < 5; i++) {
     
                 GameObject enemyInstance = Instantiate(enemy, spawnPoint.position, transform.rotation) as GameObject;
                 yield return new WaitForSeconds(0.5f);
                 Tower.enemies.Add(enemyInstance); // when I remove this line of code, it instantiates 5 enemies. But with it, it instantiates only 1... It behaves like return command in function.
             }
             yield return new WaitForSeconds(3f);
         }
     }
 }
 

And then here is Tower script... Code should check, if there is at least 1 enemy in list and if it is and is in specific range from tower, then start shoot enemy until it is destroyed:

 using UnityEngine;
 using System.Collections;
 using System.Collections.Generic;
 
 public class Tower : MonoBehaviour {
 
     public GameObject bullet;
     public static List<GameObject> enemies;
     public int time;
 
     void Start() {
 
     }
 
     void Update() {
 
         time = (int)(Time.time);
 
         if(enemies.Count > 0) {
             for(int i = 0; i < enemies.Count; i++) {
             
                 while(enemies[i].gameObject != null) { // while current object exists
 
                     if(time % 2 == 0 && (Vector3.Distance(transform.position, enemies[i].transform.position) < 2)) {
 
                         Instantiate(bullet, transform.position, transform.rotation);
                         bullet.SendMessage("Fire", enemies[i].transform.position - transform.position);
                     }
                     
                     if(Vector3.Distance(transform.position, enemies[i].transform.position) > 2) break;       
                 }
             }
         }
     }
 }


And really simple bullet script:

 using UnityEngine;
 using System.Collections;
 
 public class Bullet : MonoBehaviour {
 
     // Use this for initialization
     void Start () {
         
     }
     
     // Update is called once per frame
     public void Fire (Transform target) {
 
         rigidbody.AddForce(target.position * 1.5f * Time.deltaTime);
     }
 }

Unity writes this error, when I start the game... Really don't know what does it mean:

NullReferenceException: Object reference not set to an instance of an object GameController+c__Iterator0.MoveNext () (at Assets/Scripts/GameController.cs:39)

And when I instantiate tower, it keeps writing:

NullReferenceException: Object reference not set to an instance of an object Tower.Update () (at Assets/Scripts/Tower.cs:19)

(Saying, that error is on this line of code: if(enemies.Count > 0))

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
1
Best Answer

Answer by Fornoreason1000 · May 25, 2014 at 12:35 PM

Enemies is null, you need to initialize it. So yeah, with generic or anything at all you should initialise them for them to work. For example your boss says put this box in section null, section null doesn't exist so you can't place it there. Same things with list.

 List<GameObject> enemies = new List<GameObject>();
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 Magnomous · May 25, 2014 at 03:03 PM 0
Share

Thank you. The error NullReferenceException: Object reference not set to an instance of an object Tower.Update () (at Assets/Scripts/Tower.cs:19) has gone... But it still instantiates only 1 enemy... Still Tower.enemies.Add(enemyInstance) serves like keyword "return" in functions... In that case it is like it breaks coroutine...

avatar image Fornoreason1000 · May 25, 2014 at 03:43 PM 0
Share

Have you tried adding the yield keyword before it. Odd that it was behaving like that. Never had that happen, it could be because generics use enumeration screwing with the one the coroutine is usin. Not sure really...

avatar image Magnomous · May 25, 2014 at 05:11 PM 0
Share

And it does even not add that 1 instantiated enemy to list... When I do Debug.Log(Tower.enemies.Count) it writes 0...

And I don't actually understand what do you mean by "adding yield before it".

Could it be a Unity bug...?

avatar image Magnomous · May 25, 2014 at 05:21 PM 0
Share

Ah... $$anonymous$$e idiot... List "enemies" is in the Tower script. And tower script is component of Tower prefab. I was adding instances to variable that does not exists... At least until I instantiate Tower. Thanks for your help Fornoreason1000 anyway!

avatar image Fornoreason1000 · May 26, 2014 at 04:52 AM 0
Share

Glad you got it working, what I meant by adding the yield keyword, is to stop the break of the coroutine because you said "acts like return".

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 put gameObjects to the list? 4 Answers

C# override a destroyed GameObject in a List 1 Answer

cant get characters to load 1 Answer

Distribute terrain in zones 3 Answers

A node in a childnode? 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