• 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 Raux · Apr 24, 2014 at 05:18 PM · gameobjectinstantiatefind

Code executes once, doesn't execute a second time (while it should keep executing).

I have bumped into t$$anonymous$$s issue multiple times now, the code used to work fine earlier and I can't seem to find out what is wrong.

In a scene I have two objects, a paddle object and a brick object. The paddle object has the following code to spawn a ball from a prefab. T$$anonymous$$s prefab is set in the Unity manager to a prefab of a sphere object and t$$anonymous$$s code executes fine.

 public class PaddleScript : MonoBehaviour 
     {
         public GameObject ballPrefab;
         GameObject attachedBall;
 
         void Start(){
             SpawnBall();
         }
         
         public void SpawnBall()
         { 
             attachedBall = (GameObject)Instantiate(ballPrefab);
         }

The ball prefab has a BallScript C# script attached to it, as well as the tag "Ball". It has some properties and methods but the important part is t$$anonymous$$s:

 public class BallScript : MonoBehaviour 
     {
         public AudioClip $$anonymous$$t;
         // Again, t$$anonymous$$s $$anonymous$$t is setup in Unity.
           
         public void Die()
         {
             AudioSource.PlayClipAtPoint($$anonymous$$t, transform.position, 0.5f);
 
             PaddleScript paddleScript = GameObject.Find("Paddle").GetComponent<PaddleScript>();
             paddleScript.SpawnBall();
 
             Destroy(gameObject);
          }
     }

T$$anonymous$$s code also works perfectly fine, when Die() is called the sound plays, the gameobject is destroyed and a new ball spawns just like it does at the start of the scene. The Die() is called in another script on another gameObject:

     public class DeathFieldScript : MonoBehaviour 
     {
         void OnTriggerEnter(Collider other)
         {
             BallScript ballScript = other.GetComponent<BallScript>();
             ballScript.Die();
         }
 
     }

T$$anonymous$$s all seems fine to me and it functions, but the problem is. The following code (Class BrickScript is attached to the brick objects in the scene) executes just fine the first time, but after the ball object dies and a new one gets instantiated just like the previous one, the code returns with a NullReferenceException, even though the ball is right there in my screen and still dies like intended.

 public class BrickScript : MonoBehaviour 
     {
         public enum BrickType {Damagable, Normal, Coal, Iron, Gold, Lapis, Diamond, Chest}
         public BrickType brickType;
         public Material materialBroken;
         public AudioClip[] deathSound;
 
         public int pointValue = 1;
         public int $$anonymous$$tPoints = 1;
         private int takeDamage;
 
         void OnCollisionEnter(Collision col)
         {
             BallScript currentBall = GameObject.FindWithTag("Ball").GetComponent<BallScript>();
                             
             if (currentBall.IsUpgrade()){
                 takeDamage = 2;}
             else{
                 takeDamage = 1;}
 
             $$anonymous$$tPoints = $$anonymous$$tPoints - takeDamage;
 
             if (brickType == BrickType.Damagable && $$anonymous$$tPoints == 1){
                 AudioSource.PlayClipAtPoint(deathSound[Random.Range(0,deathSound.Length)], transform.position,0.3f);
                 t$$anonymous$$s.GetComponent<Renderer>().material = materialBroken;
             }
 
             if($$anonymous$$tPoints <= 0)
             {
                 Die ();
             }
         }
 
         void Die()
         {
             AudioSource.PlayClipAtPoint(deathSound[Random.Range(0,deathSound.Length)], transform.position,0.3f);
             Destroy(gameObject);
         }
     }

 public class InputManager : MonoBehaviour {
     
     void Update () 
         {
             if (Input.GetKeyDown(KeyCode.Z))
             {
                 BallScript cheatScript = GameObject.Find("Ball").GetComponent<BallScript>();
                 cheatScript.Die();
             }
         }
     }

Why can the two scripts above find the ball gameobject fine the first time it's instantiated, but can't find it after it dies and another ball is instantiated? It worked fine before.

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 Red Titan Studios · Apr 24, 2014 at 06:58 PM 0
Share

GameObject.Find is slow. You should use GameObject.FindWithTag. And sometimes the name can be a problem, because when you instantiate a ball prefab, it'll be called Ball_clone1 or something. And you'll be looking for "Ball" when actually its called "Ball(Clone1)". So create a tag, and assign the tag to the prefab and use findwithtag. Hopefully this helps.

1 Reply

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

Answer by EvilTak · Apr 25, 2014 at 07:55 AM

Your code in the OnCollisionEnter() function in the BrickScript is incorrect. Instead of using t$$anonymous$$s:

  BallScript currentBall = GameObject.FindWithTag("Ball").GetComponent<BallScript>(); 

Use:

 BallScript currentBall = col.gameObject.GetComponent<BallScript();

T$$anonymous$$s is done to avoid errors. Just as Red Titan Studios said, When you instantiate/clone a prefab, either "(Clone)" or "(Instance)" is added to its name. So a better and more efficient method is to use the one specified above. In case you want to find the ball (using GameObject.find or any other function like that), set the ball's tag like t$$anonymous$$s:

 public void SpawnBall()
 {
 attachedBall = (GameObject)Instantiate(ballPrefab);
 attachedBall.tag = ballPrefab.tag;
 }

 

And use FindWithTag instead of Find. T$$anonymous$$s will yield better results during runtime since you will be instantiating the ball again and again depending on your game.

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.

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

22 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

Related Questions

How to spawn a GameObject by name? 2 Answers

All subsequent instantiated objects = auto-named with suffix (Clone)? 1 Answer

Limiting respawns on scene 1 Answer

How do I instantiate same tag/name GameObjects with an array 1 Answer

Detect when instance has deleted 0 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