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 /
This question was closed Jul 30, 2014 at 08:44 AM by meat5000 for the following reason:

Self Answered

avatar image
0
Question by Vertedex · Jul 22, 2014 at 10:29 PM · c#arrayobjectselection

[SOLVED]Object selection scrip doesn't work.

I'm trying to create script that'll find objects with tag "Enemies" and put them into array, then get their transforms and put it in other array, then find the one with is nearest and finaly lookAt at this object. When i click "Play", NullReferenceExceptions start to show up and nothing happends. Please, help me get this script working!

Script:

 using UnityEngine;
 using System.Collections;
 
 public class TurretScript : MonoBehaviour {
 
     private Transform target;
     private GameObject[] enemies1;
     private Transform[] enemies2;
     private int counter;
     // Use this for initialization
     void Start () {
     
     }
     
     // Update is called once per frame
     void Update () {
         transform.LookAt (target.position);
         
         enemies1 = GameObject.FindGameObjectsWithTag ("Enemy");
 
     
         foreach(var Entities in enemies1){
             enemies2[counter] = Entities.transform; 
             counter++;
         }
         target = GetClosestEnemy (enemies2);
     }
 
     Transform GetClosestEnemy(Transform[] enemies)
     {
         Transform tMin = null;
         float minDist = 10;
         Vector3 currentPos = transform.position;
         foreach (Transform t in enemies)
         {
             float dist = Vector3.Distance(t.position, currentPos);
             if (dist < minDist)
             {
                 tMin = t;
                 minDist = dist;
             }
         }
         return tMin;
     }
 
 
 }
 
Comment
Add comment · Show 2
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 rutter · Jul 22, 2014 at 10:26 PM 0
Share

This line:

 transform.LookAt (target.position);

If that executes before you have a target set, you'll get a NullReferenceException. Once that happens, the rest of your Update function won't execute.

So... on the first frame, you don't seem to have a target, yet. Because the exception stops script execution, you won't be able to set one, either.

Fix might be as simple as a null check:

 if (target != null) {
     transform.LookAt(target.position);
 }
avatar image Vertedex · Jul 22, 2014 at 10:36 PM 0
Share

Checking if "target" isn't null kind of helped - but now other reference exception show up every frame saying that "Object reference not set to an instance of an object". It shows that the error is in line 38: "foreach (Transform t in enemies)"

2 Replies

  • Sort: 
avatar image
1

Answer by markedagain · Jul 23, 2014 at 12:37 AM

you have many issues here, one big issue is you are not reseting your "counter" that means the 2nd time it updates u are adding the same enemies over and over again and the array will keep getting bigger until it overflows.

so at some point you have to add counter = 0

another issue with this method is how would you handle once u remove enemies from the list. the array will still hold a reference to the enemy and when u try to get its position it will give u a null exception.

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
avatar image
1

Answer by Vertedex · Jul 30, 2014 at 08:06 AM

After writing it again (with much bigger knowledge), i made this:

 using UnityEngine;
 using System.Collections;
 using System;
 
 public class IfCloseEnought : MonoBehaviour {
 
     public GameObject[] enemies;
     public float range = 10;
     public float minimalDistance = 65879;
     public float measureDistance;
     public GameObject target;
     private int number;
     // Use this for initialization
     void Start () {
     
     }
     
     // Update is called once per frame
     void Update () {
         enemies = GameObject.FindGameObjectsWithTag ("Enemy");
         foreach (GameObject enemy in enemies) {
                         measureDistance = Vector3.Distance (gameObject.transform.position, enemy.transform.position);
                         if (measureDistance < minimalDistance && measureDistance < range) {
                                 target = enemy;
                                 minimalDistance = measureDistance;
                                 number++;
                         }
                 }
         if(target == null){
                 minimalDistance = 65879;
         }
         if(target != null){
             if(Vector3.Distance(gameObject.transform.position, target.transform.position) > range){
                     target = null;
             }
         }
             Array.Clear(enemies, 0, enemies.Length);
             number = 0;
             Debug.Log(target);
             Debug.Log(minimalDistance);
         
 
 
     }
 }
 

It works.

Comment
Add comment · 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 markedagain · Jul 31, 2014 at 10:28 PM 0
Share

great work on grasping the concept and thank you for closing ticket and putting proper answer :) good luck with the rest of the project

Follow this Question

Answers Answers and Comments

4 People are following this question.

avatar image avatar image avatar image avatar image

Related Questions

A problem with arrays 1 Answer

properly initializing my arrays (C#) 2 Answers

Picking a Random Order for Levers 1 Answer

Instantiate duplicates script in subsequent Objects 2 Answers

Instantiating objects from a class? (C#) 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