• 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 Airmand · Jul 29, 2011 at 03:05 PM · transformgameobjectstagsbce0019

Finding multiple gameobjects with tag error

Ok i have multiple enemies and multiple players in my scene. My problem was that when i an enemy killed a player they would stop searching for players tagged "playerguy". So i tried changing GameObject.FindWithTag("PlayerGuy").Transform to GameObject.FindGameObjectsWithTag("PlayerGuy").Transform. Problem is i get this error

`Assets/TankMan/TankManScripts/EnemyScripts/Lvl1TerroristAI.js(29,74): BCE0019: 'transform' is not a member of 'UnityEngine.GameObject[]'.

I understand why im getting this error, I just dont know how to fix it. If anyone can point me in the direction of fixing the problem that would be great.

     static var target1 : Transform;
     var moveSpeed : int = 6;  // chase speed
     var rotationSpeed : int = 1;  // speed to turn to the player
     var maxDistance : int = 10;  // attack distance
     var minDistance : int = 15;  // detection distance
     
     private var myTransform : Transform;
     
     function Awake() {
         myTransform = transform;
     }
     
     // Cache the controller 
     private var characterController : CharacterController; 
     characterController = GetComponent(CharacterController);
     
     function Start () { 
         target1 = GameObject.FindWithTag ("PlayerGuy").transform; 
         maxDistance = 2;
        
     }
     
     //------------------------------------------------------------------ 
 
     function Update(){
     if (target1 == null){
         target1 = GameObject.FindGameObjectsWithTag("PlayerGuy").transform;
         if (target1) {
         var dist = Vector3.Distance(target1.position, transform.position);
         if (dist > minDistance){  // if dist > minDistance: enters idle mode
             Idle(); 
         }
         else
         if (dist <= maxDistance) {  // if dist <= maxDistance: stop and attack        
             print ("Attack!");
 
         } 
         else {  // if maxDistance < dist < minDistance: chase the player
           //  print ("I found you "+ dist);
             myTransform.rotation = Quaternion.Slerp(myTransform.rotation,
             Quaternion.LookRotation(target1.position -                                         myTransform.position) , rotationSpeed * Time.deltaTime);
             
             // Move towards target
             characterController.Move(myTransform.forward * moveSpeed * Time.deltaTime);
             //
             //
         }
          if (dist <= maxDistance){
              myTransform.rotation = Quaternion.Slerp(myTransform.rotation,
             Quaternion.LookRotation(target1.position -                                         myTransform.position) , rotationSpeed * Time.deltaTime);
             }
         }
     }
     }
 
 //------------------------------------------------------------------
 
     var walkSpeed = 3.0; 
     var directionTraveltime = 2.0;
     var idleTime = 1.5; 
     var rndAngle = 45; 
     // enemy will turn +/- rndAngle
     
     private var timeToNewDirection = 0.0; 
     private var turningTime = 0.0; 
     private var turn: float;
     
     function Idle () { 
         // Walk around and pause in random directions unless the player is within range 
         if (Time.time > timeToNewDirection) { 
           // time to change direction? 
           if(Random.value > 0.5) // choose new direction 
               turn = rndAngle; 
          else { turn = -rndAngle; }
          turningTime = Time.time + idleTime; 
          // will stop and turn during idleTime... 
          timeToNewDirection = turningTime + directionTraveltime; 
          // and travel during directionTraveltime
        } 
        if (Time.time < turningTime) { 
            // rotate during idleTime... 
           transform.Rotate(0, turn*Time.deltaTime/idleTime, 0); 
        } else { 
           // and travel until timeToNewDirection 
           characterController.SimpleMove(transform.forward * walkSpeed); 
        }
     }
 
     function OnCollisionEnter(collision : Collision) { 
         transform.Rotate(0, turn*Time.deltaTime/idleTime, 0); 
     }


Comment
Add comment · Show 3
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 Chris D · Jul 29, 2011 at 03:35 PM 0
Share

Please go back and reformat your code. To do it properly, Paste your entire code block in, highlight it, then hit the code (101010) button.

avatar image Airmand · Jul 29, 2011 at 04:10 PM 0
Share

ah i see how to do it now. i was pressing 1010101 and then pasting the code

avatar image Chris D · Jul 29, 2011 at 06:05 PM 0
Share

Please stop posting comments as answers.

3 Replies

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

Answer by Airmand · Jul 31, 2011 at 02:33 AM

Got help from someone on the scripting forums and figured it out

 function Update () {
 
 var target1 : Transform;
 var gOs = GameObject.FindGameObjectsWithTag("PlayerGuy");
 
 if (gOs.Length > 0) {
     var closestDistance : float=Mathf.Infinity;
    for(var g : GameObject in gOs) {
         var distance : float = Vector3.Distance (transform.position, g.transform.position);
 
         if (distance < closestDistance) {
             target1 = g.transform;
             closestDistance = distance;
             }
         }
     }
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 Peter G · Jul 29, 2011 at 04:44 PM

The problem is that you can't access the Transform of a collection of GameObjects like that. You have an array of GameObjects that you found with FindGameObjectsWithTag(). To access a specific one, you need a specific GameObject, now there are a number of ways to do this.

  //The easiest
  var gOs = GameObject.FindGameObjectsWithTag("PlayerGuy");
  target1 = gOs[0].transform;
  //Get the first element in the array.

or convert the entire array. If you only need one element, this might be a waste of memory.

  //C#.
  var gOs = GameObject.FindGameObjectsWithTag("");
  var targets = Array.ConvertAll<GameObject , Transform>( gOs ,  x => x.transform );
Comment
Add comment · Show 10 · 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 Airmand · Jul 29, 2011 at 05:00 PM 0
Share

ok with this updated script i get this error and now my enemies wont move at all.

UnityException: You are not allowed to call this function when declaring a variable. $$anonymous$$ove it to the line after without a variable declaration. If you are using C# don't use this function in the constructor or field initializers, Ins$$anonymous$$d move initialization to the Awake or Start function. Lvl1TerroristAI..ctor () (at Assets/Tank$$anonymous$$an/Tank$$anonymous$$anScripts/EnemyScripts/Lvl1TerroristAI.js:3)

  var gOs = GameObject.FindGameObjectsWithTag("PlayerGuy");
  var target1 = gOs[3].transform;
 var moveSpeed : int = 6;  // chase speed
 var rotationSpeed : int = 1;  // speed to turn to the player
 var maxDistance : int = 10;  // attack distance
 var $$anonymous$$Distance : int = 1000;  // detection distance
 
 private var myTransform : Transform;
 
 function Awake() {
     myTransform = transform;
 }
 
 // Cache the controller 
 private var characterController : CharacterController; 
 characterController = GetComponent(CharacterController);
 
 function Start () { 
    target1 = gOs[3].transform; 
    maxDistance = 2;
    
 }
avatar image Peter G · Jul 29, 2011 at 06:20 PM 0
Share

There not moving because you have an error and the script won't compile properly. $$anonymous$$ove the "var gOs = ..." into the first line of the Start() function

avatar image Airmand · Jul 29, 2011 at 06:27 PM 0
Share

when i move that into start() i get a whole new slew of errors. so i moved var target 1 in the start as well and then that gave me about 10 more errors as well

avatar image Peter G · Jul 29, 2011 at 06:32 PM 0
Share

Alright, move gOs into the start function, and delete the assignment to target1 in the field initializer. Change this:

 var target1 = gOs[3].transform;

into:

 var target1;

Does gOs appear anywhere else in your code? If it does then you will need to make a few more $$anonymous$$or adjustments.

avatar image Airmand · Jul 29, 2011 at 06:41 PM 0
Share

alright i dont get any more errors but my enemies still arent moving...

var target1; var moveSpeed : int = 6; // chase speed var rotationSpeed : int = 1; // speed to turn to the player var maxDistance : int = 10; // attack distance var $$anonymous$$Distance : int = 1000; // detection distance

 private var myTransform : Transform;
 
 function Awake() {
     myTransform = transform;
 }
 
 // Cache the controller 
 private var characterController : CharacterController; 
 characterController = GetComponent(CharacterController);
 
 function Start () { 
  
  var gOs = GameObject.FindGameObjectsWithTag("PlayerGuy");
    maxDistance = 2;

Show more comments
avatar image
0

Answer by Airmand · Jul 30, 2011 at 05:03 AM

hmm in runtime i get a null reference exception object reference not set to an instance of an object. and nothing shows up in the inspector to set...

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 Peter G · Jul 30, 2011 at 04:45 PM 0
Share

well that's the problem, check if the NRE is because the gOs is null or if its because the target1 is null.

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

3 People are following this question.

avatar image avatar image avatar image

Related Questions

I'm attempting to make an array of Gameobjects with javascript but when I want to transform an object in the array, I get an error 1 Answer

Can I assign different surfaces of the same GameObject different tags?,Is it possible to make certain surfaces of GameObjects have different properties/tags? 0 Answers

Problem with transform 2 Answers

How to compare the positions of two or more instantiated gameobjects (clones) with different tags? 1 Answer

Why GameObject.Find() work and parent.transform.Find() doesn't work? 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