• 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 Osirisheaven · Oct 12, 2013 at 01:10 AM · gameobjects

How to end the game once collectable variable achieved?

Working on a school assignment where the player collects boxes and the number collected is displayed on the screen. The thing I'm running into is ending or restarting the level once the player collects "X" amounts of boxes.

Here is the CollectableObjectMaster script

 using UnityEngine;
 using System.Collections;
 
 /// <summary>
 /// Keeps track of your Collectables count & displays the count on the screen
 /// </summary>
 public class CollectableObjectMaster : MonoBehaviour 
 {
     #region Singleton
     //This is a singleton, it makes sure we always have a CollectableObjectMaster.
     private static CollectableObjectMaster collectableObjectMasterInstance = null;
 
     public static CollectableObjectMaster instance
     {
         get
         {
             if (collectableObjectMasterInstance == null)
             {
                 collectableObjectMasterInstance = FindObjectOfType(typeof(CollectableObjectMaster)) as CollectableObjectMaster;
             }
 
             if (collectableObjectMasterInstance == null)//If we didn't find a CollectableObjectMaster, make one
             {
                 GameObject newObj = new GameObject("CollectableObjectMaster");
                 collectableObjectMasterInstance = newObj.AddComponent(typeof(CollectableObjectMaster)) as CollectableObjectMaster;
                 Debug.Log("Could not find CollectableObjectMaster, so I made one");
             }
 
             return collectableObjectMasterInstance;
         }
     }
     #endregion
     
     #region Members
     [UnityEngine.SerializeField]//This allows us to inspect private members in the inspector
     private int collectablesCount;//How many collectables we have
     
     public GUIStyle collectableCountDisplayStyle;
     
     public string nameOfCollectable = "Collectable";
     #endregion
     
     #region Properties    
     public int CollectablesCount
     {
         get { return this.collectablesCount;}
         set { this.collectablesCount = value;}
     }
     #endregion
     
     
     #region Methods
     public void OnGUI()
     {        
         GUILayout.BeginArea(new Rect(0,0,Screen.width, Screen.height));
         {
             GUILayout.BeginVertical();
                 GUILayout.Space(10f);//A little buffer room ;)
                 GUILayout.BeginHorizontal();
                 {
                     GUILayout.FlexibleSpace();
                         this.DrawCollectableCount();
                     GUILayout.FlexibleSpace();
                 }
                 GUILayout.EndHorizontal();
                 GUILayout.FlexibleSpace();
             GUILayout.EndVertical();
         }
         GUILayout.EndArea();
     }
     
     private void DrawCollectableCount()
     {
         if(this.collectableCountDisplayStyle == null)
             GUILayout.Label(this.GetCollectableString());
         else
             GUILayout.Label(this.GetCollectableString(), this.collectableCountDisplayStyle);
     }
     
     private string GetCollectableString()
     {
         return (this.CollectablesCount.ToString() + " " + this.nameOfCollectable);
     }
     #endregion
 }

And here is the CollectableObject script

 using UnityEngine;
 using System.Collections;
 
 public class CollectableObject : MonoBehaviour 
 {
     void Start () 
     {
         this.gameObject.collider.isTrigger = true;//Make sure the box collider we are using is a trigger so we get OnTrigger messages
     }
     
     /// <summary>
     /// Raises the trigger enter event, this happens when colliders hit & one of them was a trigger
     /// </summary>
     /// <param name='objectHit'>
     /// Object hit.
     /// </param>
     public void OnTriggerEnter(Collider objectHit)
     {
         if(objectHit.CompareTag("Player"))//If we hit the player object, move it to spawn    
         {
             this.AddToCollectablesCount();
             this.KillMe();
         }
     }
 
     public void AddToCollectablesCount()
     {
         CollectableObjectMaster.instance.CollectablesCount++;
     }
     
     public void KillMe()
     {
         Destroy(this.gameObject);
     }
 
 }

Any advice?

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

Answer by aldonaletto · Oct 12, 2013 at 02:16 AM

A simple way is to compare the CollectablesCount value to the limit in Update (CollectableObjectMaster script):

 void Update(){
   if (CollectablesCount >= limit){
     // limit reached: place here the code to handle this
   }
 }

A more sophisticated (and slightly more efficient) way to solve the problem is to compare to the limit only when the CollectableCount value changes: since it's a property, doing this inside its set method ensures that the comparison will be made only when needed:

 public int CollectablesCount
 {
    get { return this.collectablesCount;}
    set { 
      this.collectablesCount = value;
      if (value >= limit){
         // limit reached: call a function that handles this case
         LimitReached();
      }
    }
 }

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

16 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

Related Questions

sync color change of objects c# 1 Answer

toggle gameObjects with a keyPress 1 Answer

What is the Performance implications of stacking gameobjects and switch between them for character customization. 1 Answer

Combine two or more gameobjects with different rigidbody values 0 Answers

How do I check if a boolean variable is true on a group of gameobjects with the same script? 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