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 /
  • Help Room /
avatar image
0
Question by HumanBeast · Oct 23, 2015 at 08:14 PM · c#error messagebeginnernull reference exceptionspawning-enemies

GameObject only spawning 60% of the time (c#)

I am currently working on my first unity game outside of a tutorial. I am trying to get a coin to spawn on the y axis at random positions. I have done this in c#, except the code only works some times (60% - 70% of the time). The other times the coin does not spawn and an error message saying NullReferenceException: Object reference not set to an instance of an object appears. Can you please help me.

Here is the scripts thats spawns the coin prefab:

 using UnityEngine;
 using System.Collections;
 
 public class CoinSpawner : MonoBehaviour {
 
     public GameObject Collectible;
 
     private float Miny = -2.6f;
     private float Maxy = 2.6f;
 
     // Use this for initialization
     void Start () {
         Debug.Log ("Called");
 
         spawnCoin ();
     }
      
     public void spawnCoin () {
         Vector3 coin = new Vector3 (-2.1f, Random.Range (Miny, Maxy),0);
         Instantiate (Collectible, coin, Quaternion.identity);
     }
     
     // Update is called once per frame
     void Update () {
     
     }
 }
 

Here is the script that tells the coin what to do once spawned:

 using UnityEngine;
 using System.Collections;
 
 public class CoinBehaviour : MonoBehaviour {
 
     public CoinSpawner coinSpawner;
     public int scoreValue = 1;
 
     public ScoreKeeper scoreKeeper;
 
     // Use this for initialization
     void Start () {
         // Get Score text thingy
         scoreKeeper = GameObject.Find ("0000").GetComponent<ScoreKeeper> ();
         // Get coin spawner thingy
         coinSpawner = GameObject.Find ("Spawner").GetComponent<CoinSpawner>();
     }
     
     void OnTriggerEnter2D (Collider2D col) {
 
         if (col.gameObject.tag == "Player") {
             Debug.Log ("Hit");
             Destroy (gameObject);
             coinSpawner.spawnCoin();
             scoreKeeper.Score(scoreValue);
     }
 
     
 }
 }

Picture of Game while working: alt text

Picture of Game while not working: alt text

screen-shot-2015-10-23-at-32704-pm.png (137.5 kB)
screen-shot-2015-10-23-at-32721-pm.png (236.3 kB)
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 whaleinthesea · Oct 23, 2015 at 08:20 PM 0
Share

Are you sure you have got dragged a coin prefab onto the script so there is an object to instantiate?

avatar image HumanBeast whaleinthesea · Oct 23, 2015 at 09:51 PM 0
Share

Yes. The code works most of the time but not all the time.

1 Reply

· Add your reply
  • Sort: 
avatar image
2

Answer by outasync · Oct 23, 2015 at 09:58 PM

@HumanBeast

I could be mistaken but change this:

 void OnTriggerEnter2D (Collider2D col) {
 
          if (col.gameObject.tag == "Player") {
              Debug.Log ("Hit");
              Destroy (gameObject);
              coinSpawner.spawnCoin();
              scoreKeeper.Score(scoreValue);
      }
 

to this

 void OnTriggerEnter2D (Collider2D col) {
  
          if (col.gameObject.tag == "Player") {
              Debug.Log ("Hit");
              coinSpawner.spawnCoin();
              scoreKeeper.Score(scoreValue);
              Destroy (gameObject);
      }
 

It look like you are deleting the object before calling your spawn, which I think would create the problem you are getting

Comment
Add comment · Show 3 · 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 HumanBeast · Oct 23, 2015 at 10:03 PM 0
Share

THAN$$anonymous$$ YOU SO $$anonymous$$UCH!!!!!!. That worked. Could you explain to me why.

avatar image outasync · Oct 23, 2015 at 10:07 PM 1
Share

@HumanBeast Simple really, you were destroying the object that is trying to call coinSpawner.spawnCoin(), sometimes it would work because of the way Unity handles time.

avatar image Guppie1337 outasync · Oct 24, 2015 at 02:12 AM 0
Share

I would like to expand on the reason it happens that way. I believe the best reason is it's most likely procedural. The order of events you wish to happen went from: "Detroy" ==> "$$anonymous$$ake this happen". You shouldn't have an object try to do something after it's been destroyed or you'll receive messages like that. Ins$$anonymous$$d, make sure to have it flow like: "$$anonymous$$ake this happen" ==> "It's ok to die now". Hope that clears it up a bit.

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

6 People are following this question.

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

Related Questions

C# unexpected symbol error 1 Answer

Null Reference Exception Error 1 Answer

error CS1525: Unexpected symbol `float' 1 Answer

Struggling with Unity 5 GetComponent: Null reference 0 Answers

Cascading dropdown menus 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