• 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 LetsBeChillx · May 29, 2017 at 08:36 PM · c#tagsefficiencyfindobjectoftype

More Efficient Way to Find Active GameObject

[This is coding using C#]

I've gotten a game to work, but I am using quite horrendous code to do so. I have a spawning script that checks if a simple 2D gameobject exists in the scene, and spawns one if nothing is there. here is that script:

 //Manages the spawning of the NPC gameObjects the player interacts with
 //Determines if anything is already is on the board, if not it spawns
 // a random one out of the available pool (similar to RandomBG.cs)
 
 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 
 public class SpawnManager : MonoBehaviour {
 
     private GameObject activeNPC; //The active NPC gameObject
     private GameObject nextNPC; //Next NPC gameObject to be spawned
     public GameObject[] availableNPCPool = new GameObject[9]; //Pool of the usable NPC gameobjects
 
     // Use this for initialization
     void Start ()
     {
         SpawnNPC(); //For initial spawn
     }
     
     // Update is called once per frame
     void Update ()
     {
         SpawnNPC(); //For recurring spawns
     }
 
     void SpawnNPC()
     {
         //Spawn gameObject if nothing is in the scene
         if (!activeNPC)
         {
             int randomValue = (int)(Random.Range(0, 8.9f)); //Picks a random number between 0 (inclusive) and 8; int cast is so arrary can use it
             nextNPC = availableNPCPool[randomValue]; //Sets the next NPC to spawn randomly from pool
             Debug.Log("Shape is " + randomValue);
             Instantiate(nextNPC); //Spawns gameObject with its prefab settings (i.e Transform)
         }
 
         activeNPC = Object.FindObjectOfType<MoveNPC>().gameObject; //Finds the game object with the MoveNPC script attached
     }
 }

As you can see, I am using FindObjectsOfType in Update! I know this is awful and I would use tags, but I have three different sets of tags for all nine possible spawnable objects (I use the tags for another test in another script).

My question is: would it be better to test using an if statement to test if a gameobject with either of the three tags exists, or is this fine due to the game requiring so little resources (it's literally a matching game of shapes, all basic 2D sprites)?

I know this is a weird question, but I thank all for the help regardless.

Comment
Add comment · Show 1
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 PizzaPie · May 29, 2017 at 09:12 PM 0
Share

So activeNPC is the object produced by Instantiate(nextNPC) ? Where and how do you destroy this objects?

2 Replies

· Add your reply
  • Sort: 
avatar image
-1

Answer by ritoban · Jun 02, 2017 at 01:14 PM

What exactly does your MoveNPC script do? If I understand correctly, the MoveNPC script will destroy the NPC at some point, at which point you want to spawn another random NPC.

The way I would approach this is using events, and then having the currently active MoveNPC script 'inform' anyone interested that it has destroyed itself.

MoveNPC:

 public event Action OnNPCDestroyed;
 // Called just before the gameObject is destroyed
 private void OnDestroy()
 {
     if(OnNPCDestroyed != null)
          OnNPCDestroyed(); // Will call any functions subscribed to the OnNPCDestroyed delegate when this gameObject is destroyed. 
 }

SpawnManager:

  void SpawnNPC()
  {
          int randomValue = (int)(Random.Range(0, 8.9f)); //Picks a random number between 0 (inclusive) and 8; int cast is so arrary can use it
          nextNPC = availableNPCPool[randomValue]; //Sets the next NPC to spawn randomly from pool
          Debug.Log("Shape is " + randomValue);
          GameObject npcGO =  Instantiate(nextNPC) as GameObject; //Spawns gameObject with its prefab settings (i.e Transform)
          npcGO.GetComponent<MoveNPC>().OnNPCDestroyed += SpawnNPC; // When the last NPC was destroyed, call this functions

 }

Note that I am not checking if the activeNPC gameobject is not null because when OnDestroy is called by unity, the gameobject has not yet been destroyed. You should also note that actions need to be unsubscribed. npcGO.GetComponent<MoveNPC>().OnNPCDestroyed -= SpawnNPC; The only reason I have not included this is because the gameobject holding the MoveNPC script is destroyed, so the garbage collector should clean it all up.

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 LetsBeChillx · Jun 03, 2017 at 07:03 PM 0
Share

The $$anonymous$$oveNPC script simply teleports the npc to a specific location, where a third script not attached to that object will destroy. I use the tags in this third script to decipher what shape is was and which location it landed on (for scoring). I have not begun to understand events, though I might try this method. Is there any reference material you can provide?

avatar image
2

Answer by Commoble · May 29, 2017 at 09:48 PM

You can avoid searching for objects during runtime by keeping references to your objects in variables. You can do this by using something along the lines of:

 if (this.activeNPC == null)
 {
     this.activeNPC = Instantiate(nextNPC);
 }

Instantiate returns a reference to the object instantiated; if you store this reference in a variable, you don't have to use Find-like searching to find your instantiated object.

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 LetsBeChillx · Jun 03, 2017 at 06:59 PM 0
Share

I am already using that code lol check lines 30 to 35. What I am doing the check is to see whether the exists an NPC in the scene already, so using references would not work here.

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

9 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Multiple Cars not working 1 Answer

Distribute terrain in zones 3 Answers

How to spawn an animal at each transform of a gameobject with a tag position in another scene? 0 Answers

Coroutine Array, set to null or initialize new array 1 Answer

Making a bubble level (not a game but work tool) 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