• 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
Question by Malfegor · Jan 21, 2013 at 01:20 PM · listnullreferenceexeption

List search gives null

Hello, i've got an issue here and might need some help with it. First my code: using UnityEngine; using System.Collections;

 public class AttackTowerAimAndShoot : MonoBehaviour {
     
     public float reload = 1F;
     public float firePause = 0.25F;
     public GameObject effect;
     public float amount = 0.001F;
     Transform target;
     Transform[] muzzlePositions;
     Transform turretTurnPoint;
     float newFireTime;
     float newMoveTime;
     private Quaternion rotation;
     private float aimError;
     GameObject projectile;
     public float range = 500F;
     // Use this for initialization
     void Start () {
         Transform muzzle1 = transform.FindChild("MuzzlePos1");
         Transform muzzle2 = transform.FindChild("MuzzlePos2");
         turretTurnPoint = transform.FindChild("Turret");
     }
     
     // Update is called once per frame
     void Update () {
         if (target == null)
             return;
         if (target != null)
         {
             transform.LookAt(target);
             newFireTime = Time.time + (reload * 0.5F);
             if (Time.time >= newFireTime)
             {
                 Fire ();    
             }
         }
         GetTargetEnemy();
     }
     
     void Fire ()
     {
         newFireTime = Time.time + reload;
         newMoveTime = Time.time + firePause;
         //CalculateAimError();
         for (int i = 0; i < muzzlePositions.Length; i++) 
         {
             projectile = Instantiate (Resources.Load("Bullet"), muzzlePositions[i].position, muzzlePositions[i].rotation) as GameObject;
             effect = Instantiate (Resources.Load("FireMuzzle"), muzzlePositions[i].position, muzzlePositions[i].rotation) as GameObject;
         }
     }
     void GetTargetEnemy()
     {
         for (int i = 0; i < StaticVariables.enemies.Count; i++)
         {
             if(StaticVariables.enemies[i].transform == null)
             {
                 StaticVariables.enemies.Remove(StaticVariables.enemies[i]);
                 continue;
             }
             
             if(Vector3.Distance (StaticVariables.enemies[i].position, transform.position) < range)
             {
                 //Debug.Log(Vector3.Distance (StaticVariables.enemies[i].position, transform.position));
                 target = StaticVariables.enemies[i];
                 break;
             }
         }

The problem is with the last part: The void GetTargetEnemy(). I want my towers to search through a list for a target. Though, the enemies[i] always returns 'null', so my towers don't get a new target. I don't understand any of it and I get a NullReferenceException at the Vector3.Distance check all the time. Any help or word of advice is welcome. Thanks in advance!

Comment

People who like this

0 Show 5
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 dorpeleg · Jan 21, 2013 at 01:29 PM 0
Share

Where are you defining enemy[]? I can't see it.

avatar image Malfegor · Jan 21, 2013 at 01:43 PM 0
Share

Oh, sorry, that's in another code... My list: public static List enemies = new List();

And the line of code in which I fill the List:

void Spawn() { for (int i = 0; i < spawnPoints.Length; i++) { enemy = Instantiate (Resources.Load("Enemy"), spawnPoints[i].position, spawnPoints[i].rotation) as Transform;

 StaticVariables.enemies.Add(enemy);
 Debug.Log("Enemies " + StaticVariables.enemies.Count);
 }

}

Spawning the enemy and adding it directly in the list (I think it does that, at least)

avatar image Malfegor · Jan 21, 2013 at 01:47 PM 0
Share

Sorry for the messy script part and in the enemy = Instantiate part enemy is defined as a Transform

avatar image dorpeleg · Jan 21, 2013 at 02:20 PM 0
Share

I don't see any List in unity, but there is ArrayList (which I think functions the same). Is that what your are using?

avatar image whydoidoit · Jan 21, 2013 at 02:34 PM 0
Share

@dorpeleg List is a generic list available in Unity and should always be used instead of ArrayList

2 Replies

· Add your reply
  • Sort: 
avatar image

Answer by whydoidoit · Jan 21, 2013 at 02:38 PM

My guess is that you enemies are getting nulled as they are destroyed.

Given you didn't format your code quite right it's hard to see if your enemy list is

   List<Transform> enemies = new List<Transform>();

Presuming it is then I would suggest that you change you loop to look like this:

   for(int i = StaticVariables.enemies.Count-1; i>= 0; i--)
   {
        if(StaticVariables.enemies[i] == null) //Not .transform
        {
             enemies.RemoveAt(i);
             continue;
        }
        //distance check etcetera
        
Comment
Bunny83

People who like this

1 Show 1 · 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 Malfegor · Jan 21, 2013 at 04:25 PM 0
Share

Yes, this does make sense, it's still not working propperly, though... My NullReferenceException is gone (and I think I also get the logic behind this For loop) but my 'towers' still don't get a target through... I don't know if this is because I tell the script to look at the distance of the [i] instead of pointing to a Transform object in the first place, but i don't know how to fix this... Is there any way to fix this, or can you give me a hint for another option? Or should i ask this in another question? Anyway: thank you for letting me know the secret behind the NullReference mystery! :D

avatar image

Answer by Malfegor · Jan 30, 2013 at 08:35 AM

Fixed the problem: I spawned the enemies as Transforms and (I don't know why this happened) they where made null as soon as they entered the list. All i had to do was modify this part:

 public Transform enemy;
 enemy = Instantiate (Resources.Load("FastEnemy"), spawnPoints[i].position, spawnPoints[i].rotation)

To this:

 GameObject newEnemy = Instantiate (Resources.Load("FastEnemy"), spawnPoints[i].position, spawnPoints[i].rotation) as GameObject;
             enemy = newEnemy.transform;

And then add it to the list :)

Comment

People who like this

0 Show 0 · 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

11 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

Related Questions

A node in a childnode? 1 Answer

Edit each Parameter Class on Function 1 Answer

javascript, default object comparator 1 Answer

Issues outputting a list of strings 1 Answer

C# List and GUI 3 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