Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 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
1
Question by ivt18 · Nov 17, 2017 at 09:09 PM · 2d gameunity 2dnot workingtagfindgameobjectwithtag

GameObject.FindGameObjectWithTag not finding the tagged objects.

Alright, so I'm trying to make a simple spaceship game with enemies n' stuff, including meteors. What I've done is I've put different empty GameObjects arount the 'map' from which the meteors will spawn. I assign the meteor prefab, and from there try to find it's transform and image through FindGameObjectsWithTag, however it doesn't seem to be finding anything. Here's my code:

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 
 public class MeteorBehaviour : MonoBehaviour
 {
 
     public GameObject meteor;
     private Transform meteorTransform;
     public Transform meteorImage;
     private float moveSpeed;
     private float spinSpeed;
     // Use this for initialization
     void Start()
     {
         if(meteor != null)
         {
             meteorImage = GameObject.FindGameObjectWithTag("Meteor Image").GetComponent<Transform>();
             meteorTransform = GameObject.FindGameObjectWithTag("Meteor").GetComponent<Transform>();
         }
         moveSpeed = 0.05f;
         spinSpeed = -50;
         //Debug.Log();
     }
     // Update is called once per frame
     void Update()
     {
         Vector2 meteorDirection = new Vector2(35, 43);
         if (meteor != null)
         {
             meteorTransform.transform.Translate(meteorDirection * moveSpeed * Time.deltaTime);
             if(meteorImage != null)
             {
                 meteorImage.transform.Rotate(Vector3.forward, spinSpeed * Time.deltaTime);
             }
             Vector3 meteorPos = Camera.main.WorldToViewportPoint(meteor.transform.position);
             if (meteorPos.x <= 0f || meteorPos.y <= 0f && meteor != null && meteor != null)
             {
                 Destroy(meteor);
             }
             if (meteorPos.x >= 1f || meteorPos.y >= 1f && meteor != null && meteor != null)
             {
                 Destroy(meteor);
             }
         }
     }
 }
Comment
Add comment · Show 16
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 dan_wipf · Nov 18, 2017 at 07:08 AM 0
Share

Hi well i see why it doesn't work, because your if Statement is unreachable, if you want to add $$anonymous$$eteor GameObject on Runtime. You need to define your Public $$anonymous$$eteor GameObject, bevor pressing Play. You Have now two Options


Nr1 = Take Out your if Statement in the Starte Line like :

 void Start()
     {
         
     meteorImage = GameObject.FindGameObjectWithTag("$$anonymous$$eteor Image").GetComponent<Transform>();
     meteorTransform = GameObject.FindGameObjectWithTag("$$anonymous$$eteor").GetComponent<Transform>();
         
         moveSpeed = 0.05f;
         spinSpeed = -50;
         //Debug.Log();
     }



Nr2 = You put your If Statement in you Update Section like:

 void Update()
     {
 {
     meteorImage = GameObject.FindGameObjectWithTag("$$anonymous$$eteor Image").GetComponent<Transform>();
     meteorTransform = GameObject.FindGameObjectWithTag("$$anonymous$$eteor").GetComponent<Transform>();
         }
 
 
         Vector2 meteorDirection = new Vector2(35, 43);
         if (meteor != null)
         {
             meteorTransform.transform.Translate(meteorDirection * moveSpeed * Time.deltaTime);
             if(meteorImage != null)
             {
                 meteorImage.transform.Rotate(Vector3.forward, spinSpeed * Time.deltaTime);
             }
             Vector3 meteorPos = Camera.main.WorldToViewportPoint(meteor.transform.position);
             if (meteorPos.x <= 0f || meteorPos.y <= 0f && meteor != null && meteor != null)
             {
                 Destroy(meteor);
             }
             if (meteorPos.x >= 1f || meteorPos.y >= 1f && meteor != null && meteor != null)
             {
                 Destroy(meteor);
             }
         }
     }

Well this is what i came up with in the end..


 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 
 public class $$anonymous$$eteorBehaviour : $$anonymous$$onoBehaviour
 {
 
     public GameObject meteor;
     Transform meteorTransform;
     public Transform meteorImage;
     private float moveSpeed;
     private float spinSpeed;
 
 
     void Start()
     {
     meteorImage = GameObject.FindGameObjectWithTag("$$anonymous$$eteor Image").GetComponent<Transform>();
     meteorTransform = GameObject.FindGameObjectWithTag("$$anonymous$$eteor").GetComponent<Transform>();
 
         moveSpeed = 0.05f;
         spinSpeed = -50;
     }
 
     void Update()
     {
         Vector2 meteorDirection = new Vector2(35, 43);
         if (meteor != null)
         {
             meteorTransform.transform.Translate(meteorDirection * moveSpeed * Time.deltaTime);
             if(meteorImage != null)
             {
                 meteorImage.transform.Rotate(Vector3.forward, spinSpeed * Time.deltaTime);
             }
             Vector3 meteorPos = Camera.main.WorldToViewportPoint(meteor.transform.position);
 
             if (meteor != null) {
                 if (meteorPos.x <= 0f || meteorPos.y <= 0f) {
                     Destroy (meteor);
                 }
                 if (meteorPos.x >= 1f || meteorPos.y >= 1f) {
                     Destroy (meteor);
                 }
             }
         }
     }
 }


avatar image ivt18 dan_wipf · Nov 18, 2017 at 06:37 PM 0
Share

I just tried it and it still didn't work, thanks for the answer tho :)

avatar image dan_wipf dan_wipf · Nov 18, 2017 at 07:24 PM 0
Share

Are there multiple GameObjects who share the same tag?

avatar image ivt18 dan_wipf · Nov 18, 2017 at 09:12 PM 0
Share

No, there's only this one meteor and it's image, both assigned to a different tag.

Show more comments
avatar image dan_wipf dan_wipf · Nov 18, 2017 at 07:36 PM 0
Share

and just to be sure, have you created your own tag and asigned them to you gameobject?

avatar image ivt18 dan_wipf · Nov 18, 2017 at 09:13 PM 0
Share

Yup, created a $$anonymous$$eteor and a $$anonymous$$eteor Image tag, and then assigned them to their corresponding game object.

avatar image pako · Nov 18, 2017 at 07:06 PM 0
Share

@IliyanVT18 I'm a bit confused with your question.

  1. Is the $$anonymous$$eteorBehaviour script attached on each of the GameObjects from which the meteors will spawn?

  2. You say that you try to find it's transform and image through FindGameObjectsWithTag (plural objects) but then in your code you don't use FindGameObjectsWithTag but FindGameObjectWithTag

  3. You say that you assign the meteor prefab, but you don't Instantiate the meteor prefab anywhere in your code.

  4. IF you had instantiated the meteor prefab in the scene, why would you be wanting to find its Transform using`FindGameObjectWithTag`? You would already have a reference to the instance in the scene.

  5. FindGameObjectWithTag is used to find GameObjects that are already in the scene. So, if that were the case, why would you want the meteor prefab, which you don't even Instantiate?

$$anonymous$$y guess is that your code is not finding any meteors in the scene, because there are no meteors in the scene.

It would be very helpful to you if you took some Unity tutorials: https://unity3d.com/learn/tutorials https://unity3d.com/learn

avatar image ivt18 pako · Nov 19, 2017 at 03:53 PM 0
Share

I didn't make it clear in the question. I have a separate meteor spawner script which instantiates the meteor prefab, here it is:

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 
 public class $$anonymous$$eteorSpawner : $$anonymous$$onoBehaviour
 {
     public GameObject[] spawnPoints = null;
     public GameObject meteor = null;
     int max$$anonymous$$eteorsOnScreen = 1;
     public int current$$anonymous$$eteorsOnScreen = 0;
     public float interval = 10f;
     int position;
     Transform point;
     // Use this for initialization
     void Start()
     {
         if (spawnPoints == null && meteor != null)
         {
             spawnPoints = GameObject.FindGameObjectsWithTag("Spawn Points");  
         }
     }
 
     // Update is called once per frame
     void Update()
     {
         InvokeRepeating("spawn$$anonymous$$eteor", 0.0f, interval);
     }
     void spawn$$anonymous$$eteor()
     {
         position = (int)Random.Range(0, spawnPoints.Length - 1);
         Transform point = spawnPoints[position].GetComponent<Transform>();
         if (spawnPoints != null && current$$anonymous$$eteorsOnScreen < max$$anonymous$$eteorsOnScreen)
         {
             Vector3 spawn = new Vector3(point.position.x, point.position.y, 0.0f);
             Instantiate(meteor, spawn, Quaternion.identity);
             current$$anonymous$$eteorsOnScreen++;
         }
 
     }
 }

avatar image ivt18 pako · Nov 19, 2017 at 03:54 PM 0
Share

The meteor behaviour script is attached to an empty game object in the scene, called meteor controller. There I put both the meteor behaviour and spawner scripts, and assigned the mandatory prefabs and transforms to them.

avatar image pako · Nov 19, 2017 at 05:09 PM 0
Share

The main problem is that you are instantiating the meteors by calling InvokeRepeating("spawn$$anonymous$$eteor", 0.0f, interval); from inside the $$anonymous$$eteorSpawner.Update(). Since all Start()methods are called before Update(), there will be no meteors spawned yet, when $$anonymous$$eteorBehaviour.Start() executes, as GameObject.FindGameObjectWithTag is called inside Start(). Another problem is that you don't know which of the 2 scripts $$anonymous$$eteorSpawner and $$anonymous$$eteorBehaviour will be executed first. They are both on the same GameObject, and even if you put InvokeRepeating("spawn$$anonymous$$eteor", 0.0f, interval) inside $$anonymous$$eteorSpawner.Start() (and you should - see below). $$anonymous$$eteorBehaviour.Start() might execute before $$anonymous$$eteorSpawner.Start(), so the problem won't go away. You could of course, set the Script Execution Order of the two scripts, so that $$anonymous$$eteorSpawner executes before $$anonymous$$eteorBehaviour. However, I always prefer to use setting of the Script Execution Order as a last resort, only if I can't find a better solution. So, personally, I would rather have a reference assigned of the $$anonymous$$eteorSpawner inside $$anonymous$$eteorBehaviour:

 private $$anonymous$$eteorSpawner meteorSpawner// use GetComponent<$$anonymous$$eteorSpawner>() to get reference

and then use meteorSpawner.meteor to access the meteor. Anyway, it's up to you, setting of the Script Execution Order will work too. Also, as I said above, maybe you should consider calling InvokeRepeating("spawn$$anonymous$$eteor", 0.0f, interval) from inside Start(), rather than Update(). Otherwise, you'll be spawning 1 meteor every 10 seconds, at every frame. e.g. if FPS = 60, after 1 second you will have started InvokeRepeating 60 times, and you'll be spawning 60 meteors every 10 seconds. Imagine after 10 seconds, you'll spawn 600 meteors every seconds, etc.

EDIT: Having said that, and thinking "out of the box". I believe that it would be a better solution if you attached the $$anonymous$$eteorBehaviour script directly on the meteor prefab. So, that each meteor handled its own movement. You could also setup 6 trigger colliders around the play area, to act as the boarders of the game. So, you could then use OnTriggerEnter to destroy the meteors, ins$$anonymous$$d of having code inside Update().

avatar image ivt18 pako · Nov 19, 2017 at 05:31 PM 0
Share

Thank you very much for the answer, but I just found a very simple fix to this problem. I just modified slightly the $$anonymous$$eteorBehaviour script so that it's in the meteor object itself. Here's the fixed code:

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 
 public class $$anonymous$$eteorBehaviour : $$anonymous$$onoBehaviour
 {
     private GameObject meteor;
     private Transform meteorTransform;
     private Transform meteorImage;
     private float moveSpeed;
     private float spinSpeed;
     $$anonymous$$eteorSpawner meteorSpawner;
     // Use this for initialization
     void Start()
     {
         moveSpeed = 0.05f;
         spinSpeed = -50;
         meteor = gameObject;
         meteorTransform = gameObject.GetComponent<Transform>();
         meteorSpawner = GameObject.FindGameObjectWithTag("$$anonymous$$eteor Controller").GetComponent<$$anonymous$$eteorSpawner>();
         meteorImage = transform.Find("meteor-sprite");
         //Debug.Log();
     }
     // Update is called once per frame
     void Update()
     {      
         Vector2 meteorDirection = new Vector2(35, 43);
         if (meteor != null)
         {
             if (meteorTransform != null)
             {
                 meteorTransform.transform.Translate(meteorDirection * moveSpeed * Time.deltaTime);
             }
             if (meteorImage != null)
             {
                 meteorImage.transform.Rotate(Vector3.forward, spinSpeed * Time.deltaTime);
             }
             Vector3 meteorPos = Camera.main.WorldToViewportPoint(meteor.transform.position);
             if (meteorPos.x <= 0f || meteorPos.y <= 0f && meteor != null && meteor != null)
             {
                 Destroy(meteor);
                 if (meteorSpawner != null)
                 {
                     meteorSpawner.current$$anonymous$$eteorsOnScreen--;
                 }
             }
             if (meteorPos.x >= 1f || meteorPos.y >= 1f && meteor != null && meteor != null)
             {
                 Destroy(meteor);
                 if (meteorSpawner != null)
                 {
                     meteorSpawner.current$$anonymous$$eteorsOnScreen--;
                 }
             }
         }
     }
 }

And thanks for the InvokeRepeating fix, that was another problem I was having just now.

avatar image ivt18 pako · Nov 19, 2017 at 05:39 PM 0
Share

I just posted an answer about attaching the script directly to the gameobject. We're connected XD Also thanks for the collider boundary idea. Gonna use it in 3D Games

1 Reply

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

Answer by ivt18 · Nov 19, 2017 at 05:38 PM

Finally found an ez fix, I just modified the MeteorBehaviour script slightly so that it could be in the meteor gameobject itself. Another problem I was having was with the MeteorSpawner (mentioned in one of the comments), where I would invoke meteors from Update();, rather than from Start();. Thanks to everybody who helped out in this thread. Here are the two fixed scripts: MeteorBehaviour:

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 
 public class MeteorBehaviour : MonoBehaviour
 {
     private GameObject meteor;
     private Transform meteorTransform;
     private Transform meteorImage;
     private float moveSpeed;
     private float spinSpeed;
     MeteorSpawner meteorSpawner;
     // Use this for initialization
     void Start()
     {
         moveSpeed = 0.05f;
         spinSpeed = -50;
         meteor = gameObject;
         meteorTransform = gameObject.GetComponent<Transform>();
         meteorSpawner = GameObject.FindGameObjectWithTag("Meteor Controller").GetComponent<MeteorSpawner>();
         meteorImage = transform.Find("meteor-sprite");
         //Debug.Log();
     }
     // Update is called once per frame
     void Update()
     {      
         Vector2 meteorDirection = new Vector2(35, 43);
         if (meteor != null)
         {
             if (meteorTransform != null)
             {
                 meteorTransform.transform.Translate(meteorDirection * moveSpeed * Time.deltaTime);
             }
             if (meteorImage != null)
             {
                 meteorImage.transform.Rotate(Vector3.forward, spinSpeed * Time.deltaTime);
             }
             Vector3 meteorPos = Camera.main.WorldToViewportPoint(meteor.transform.position);
             if (meteorPos.x <= 0f || meteorPos.y <= 0f && meteor != null && meteor != null)
             {
                 Destroy(meteor);
                 if (meteorSpawner != null)
                 {
                     meteorSpawner.currentMeteorsOnScreen--;
                 }
             }
             if (meteorPos.x >= 1f || meteorPos.y >= 1f && meteor != null && meteor != null)
             {
                 Destroy(meteor);
                 if (meteorSpawner != null)
                 {
                     meteorSpawner.currentMeteorsOnScreen--;
                 }
             }
         }
     }
 }

MeteorSpawner:

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 
 public class MeteorSpawner : MonoBehaviour
 {
     public GameObject[] spawnPoints = null;
     public GameObject meteor = null;
     int maxMeteorsOnScreen = 1;
     public int currentMeteorsOnScreen = 0;
     public float interval = 10f;
     int position;
     Transform point;
     // Use this for initialization
     void Start()
     {
         if (spawnPoints == null && meteor != null)
         {
             spawnPoints = GameObject.FindGameObjectsWithTag("Spawn Points");
         }
         InvokeRepeating("spawnMeteor", 0.0f, interval);
     }
     void spawnMeteor()
     {
         position = (int)Random.Range(0, spawnPoints.Length - 1);
         Transform point = spawnPoints[position].GetComponent<Transform>();
         if (spawnPoints != null && currentMeteorsOnScreen < maxMeteorsOnScreen)
         {
             Vector3 spawn = new Vector3(point.position.x, point.position.y, 0.0f);
             Instantiate(meteor, spawn, Quaternion.identity);
             currentMeteorsOnScreen++;
         }
         if (currentMeteorsOnScreen > maxMeteorsOnScreen)
         {
             Destroy(meteor);
         }
     }
 }

Hope this helps anybody else having problems.

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.

Follow this Question

Answers Answers and Comments

82 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 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 fix this error 2 Answers

good tutorials for 2d action rpg?,Good tutorials on 2D action-rpg? 1 Answer

Inconsistent Mouse Related Behavior in 2D 1 Answer

Match 3 game getting the colour of the match 1 Answer

Trigger not working with a specific game object 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