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 Mat7itan · Mar 01, 2017 at 08:48 PM · c#script.exception

Decrementing a variable in a script in which it was not declared.

I am trying to control the number of enemies that can be in my game at any given time. Within the script that controls spawning I have a public static variable named enemyCount (the script is attached to multiple objects) that is incremented by 1 every time an enemy is spawned, and when enemyCount reaches the maximum allowed enemies then enemies stop spawning. How can I decrement this variable by 1 within my script that controls when an enemy loses health and ultimately dies? Everything I have tried up to this point has given me a NullReferenceException: Object reference not set to an instance of an object.

I have left in an example of what I tried to decrement the value, and that gave me the exception.

Script that controls enemy spawn: public class SpawnerManager : MonoBehaviour { public PlayerHealth playerHealth; public GameObject enemy; public Transform spawnPoint;

 public float spawnTime;
 private static int enemyCount = 1;

 public int EnemyCount
 {
     get { return enemyCount; }
     set { enemyCount += value; }
 }

 private void OnEnable()
 {
     StartCoroutine(ExecuteAfterTime());
 }

 IEnumerator ExecuteAfterTime()
 {
     spawnTime = Random.Range(3, 7);
     yield return new WaitForSeconds(spawnTime);

     if (enemyCount < 5)
     {
         Instantiate(enemy, spawnPoint.position, spawnPoint.rotation);
         enemyCount++;
     }

     StartCoroutine(ExecuteAfterTime());
 }

}

Script that controls enemy health, death, etc: public class EnemyHealth : MonoBehaviour { public int startingHealth = 100; public int currentHealth; public float sinkSpeed = 2.5f; public int scoreValue = 10;

 public AudioClip deathClip;

 Animator anim;
 AudioSource enemyAudio;
 ParticleSystem hitParticles;
 CapsuleCollider capsuleCollider;
 SpawnerManager spawnerManager;

 private bool isDead;
 private bool isSinking;


 void Awake ()
 {
     anim = GetComponent <Animator> ();
     enemyAudio = GetComponent <AudioSource> ();
     hitParticles = GetComponentInChildren <ParticleSystem> ();
     capsuleCollider = GetComponent <CapsuleCollider> ();
     spawnerManager = GetComponent<SpawnerManager>();

     currentHealth = startingHealth;
 }


 void Update ()
 {
     if(isSinking)
     {
         transform.Translate (-Vector3.up * sinkSpeed * Time.deltaTime);
     }
 }


 public void TakeDamage (int amount, Vector3 hitPoint)
 {
     if(isDead)
         return;

     enemyAudio.Play ();

     currentHealth -= amount;
         
     hitParticles.transform.position = hitPoint;
     hitParticles.Play();

     if(currentHealth <= 0)
     {
         Death ();
     }
 }


 public void Death ()
 {
     isDead = true;

     capsuleCollider.isTrigger = true;

     anim.SetTrigger ("Dead");

     enemyAudio.clip = deathClip;
     enemyAudio.Play ();

     spawnerManager.EnemyCount = -1;
 }


 public void StartSinking ()
 {
     GetComponent <UnityEngine.AI.NavMeshAgent> ().enabled = false;
     GetComponent <Rigidbody> ().isKinematic = true;
     isSinking = true;
     ScoreManager.score += scoreValue;
     Destroy (gameObject, 2f);
 }

}

Comment
Add comment
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

1 Reply

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

Answer by UnityCoach · Mar 01, 2017 at 08:55 PM

As this is a static property, you need to access it at class level, not instance level. You probably meant to write :

 SpawnerManager.EnemyCount = -1;

instead of

 spawnerManager.EnemyCount = -1;

as spawnerManager is obviously an instance of SpawnerManager

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 UnityCoach · Mar 01, 2017 at 08:58 PM 0
Share

Sorry, I misread you code.

In fact, what appears odd to me is this :

 public int EnemyCount
  {
      get { return enemyCount; }
      set { enemyCount += value; }
  }

I would expect that :

 public int EnemyCount
  {
      get { return enemyCount; }
      set { enemyCount = value; }
  }
avatar image UnityCoach UnityCoach · Mar 01, 2017 at 09:00 PM 0
Share

And then :

 spawner$$anonymous$$anager.EnemyCount -= 1;
avatar image Mat7itan · Mar 01, 2017 at 09:08 PM 0
Share

Thank you! This fixed it.

I have set { enemyCount += value; } so that the value that the variable enemyCount is set to has 1 subtracted from it when an enemy dies. If set { enemyCount = value; } then enemyCount becomes -1 and will essentially allow infinite enemy spawns as long as the player keeps killing them because enemyCount will never reach the value for the maximum number of enemies.

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

317 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 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 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 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

Unity freeze when open script,I keep trying to open a script, but it freezes Unity. Please help. 1 Answer

Okay, I am very new to Unity but whenever i try something it called an error on the brackets but there is nothing wrong with them. 1 Answer

How to make object spawn only once? 1 Answer

Unity Video Ads after a few times of gameplay. 0 Answers

Can someone please help me find out what wrong with my code. 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