• 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 alphamalet · Feb 14, 2016 at 10:18 PM · exception

KeyNotFound Exception only in build!

I am making a Kinect game in Unity and it works fine in the editor. When I build the game, however, I get this error at runtime when a specific function (which work in the editor) is called: "KeyNotFoundException: The given key was not present in the dictionary." Like I said, everything works fine in the editor! Why does this not work in the build?

Below is the code I'm using. The function that is throwing the exception is the "CreatePlayer" function on line 129 ( Destroy(playerRepresentations[key]);)

 using UnityEngine;
 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine.Audio;
 public class SetPlayer : MonoBehaviour {
     GameObject thePlayer;
     public float minX;
     public float maxX;
     public float minZ;
     public float maxZ;
     private List<GameObject> thePlayers = new List<GameObject>();
     public Dictionary<GameObject, GameObject> playerRepresentations = new Dictionary<GameObject, GameObject>();
     GameObject spine;
     public float xOffSet;
     public float zOffSet;
     public float TheZOffset;
     public float xPos;
     public float zPos;
     public float TheXOffset;
 
     public float curentZ;
     private float framesHeld;
     private bool resetDictionary;
     private bool canUseAbility;
     public GameControllerScript gameController;
     public bool gameStart = true;
 
     public AudioClip playerGot;
     public AudioMixerGroup output1;
     // Use this for initialization
     void Start () {
         TheXOffset = -.81f;
         TheZOffset = 0.07f;
     }
 
     void OnGUI(){
 
     }
     
     // Update is called once per frame
     void Update () {
 //        print (thePlayers.Count);
         print (playerRepresentations.Count);
         //loop through each player
         try{
             int i = 0;
             foreach(GameObject key in thePlayers){
                 if (key != null) {
                     //get the spine 
                     spine = key.transform.Find ("SpineBase").transform.gameObject;
                     GameObject rightWrist = key.transform.Find("WristRight").transform.gameObject;
                     GameObject leftWrist = key.transform.Find("WristLeft").transform.gameObject;
                     GameObject knee = key.transform.Find("KneeLeft").transform.gameObject;
                     //calculate a normailized offset based on the min and max positions on the screen
                     xPos = (spine.transform.position.x -minX) / (maxX -minX) - TheXOffset;
                     zPos = (spine.transform.position.z -minZ) / (maxZ -minZ) - TheZOffset;
                     //apply the offset
                     if(zPos < 1)
                         playerRepresentations[key].transform.position = new Vector3 (-spine.transform.position.x + ((xPos) * xOffSet), spine.transform.position.y, spine.transform.position.z + (zPos * zOffSet));
 
                     curentZ = spine.transform.position.z;
                     if(canUseAbility && zPos < .8f && playerRepresentations.Count == 2){
                         if(leftWrist.transform.position.y < knee.transform.position.y || rightWrist.transform.position.y < knee.transform.position.y){
                             framesHeld++;
                             if(framesHeld == 4){
                                 print ("ACTIVATE ABILITY");
                                 gameController.StartCoroutine(gameController.ActivateAbility(playerRepresentations[key].transform.position));
                                 canUseAbility = false;
                                 framesHeld = 0;
                             }
                         }
                     }
                     else
                         framesHeld = 0;
                 }
                 print (framesHeld);
             }
         }catch(System.Exception){}
 
     }
     //called in body source view by the create body function
     public void CreatePlayer(ulong trackingID)
     {
         //if there are less thatn 2 players
         if (thePlayers.Count >= 2) {
             return;
         }
         //PlayerGot Sound
         AudioSource playerGotten = gameObject.AddComponent<AudioSource> ();
         playerGotten.clip = playerGot;
         playerGotten.outputAudioMixerGroup = output1;
         playerGotten.Play ();
         Destroy (playerGotten, playerGot.length);
         //place the player's body created by the kinect in the list
         thePlayers.Add (GameObject.Find ("Body:" + trackingID));
         GameObject myPlayer = GameObject.Find ("Body:" + trackingID);
         foreach (MeshRenderer theRenderer in myPlayer.transform.GetComponentsInChildren<MeshRenderer>()) {
             theRenderer.enabled = false;
         }
 
     
 
         try{
             //rotate the player
             thePlayers[thePlayers.IndexOf(myPlayer)].transform.eulerAngles = new Vector3(0,180,0);
             //create the player representation and position it correctly
             print("player rep Created");
             playerRepresentations.Add(myPlayer,(GameObject)Instantiate(Resources.Load ("Cube") )as GameObject);
             playerRepresentations[myPlayer].transform.parent = thePlayer.transform.Find ("SpineBase").transform;
             playerRepresentations[myPlayer].transform.position = new Vector3(spine.transform.position.x,spine.transform.position.y,spine.transform.position.z);
 
 
         
         }
         catch(System.Exception){
         }
 
         print (playerRepresentations.Count +"is count");
         if(gameStart){
             StartCoroutine(removeStartPoint(playerRepresentations[myPlayer]));
         }
 
         //remove any player represenation that shoud no longer be there due to the player being lost
         List<GameObject> keys = new List<GameObject> (playerRepresentations.Keys);
         Dictionary<GameObject, GameObject> tempDictionary = new Dictionary<GameObject, GameObject>();
         foreach (GameObject key in keys) {
             if(!thePlayers.Contains(key)){
                 if(thePlayers.Count >=2){
                     Destroy(playerRepresentations[key]);
                     resetDictionary = true;
                 }
             }
             else
                 tempDictionary.Add(key,playerRepresentations[key]); 
         }
 
         if(resetDictionary){
             playerRepresentations.Clear();
             playerRepresentations = tempDictionary;
             resetDictionary = false;
         }
 
        
     }
 
     public void DestroyPlayer(ulong trackingID){
         print ("destroy player Id: " + trackingID);
         thePlayers.Remove (GameObject.Find ("Body:" + trackingID));
     }
 
     public byte GetNumberOfActivePlayers(){
         return (byte)playerRepresentations.Count;
     }
 
     private IEnumerator removeStartPoint(GameObject thePlayer){
         yield return new WaitForSeconds (.1f);
         print(thePlayer.transform.position +"is position");
         try{
             if(playerRepresentations.Count == 1){
                 if(Vector3.Distance(thePlayer.transform.position, GameObject.Find("Player1Stand").transform.position) < Vector3.Distance(thePlayer.transform.position, GameObject.Find("Player2Stand").transform.position))
                     Destroy(GameObject.Find("Player1Stand"));
                 else
                     Destroy(GameObject.Find("Player2Stand"));
             }
             else if(playerRepresentations.Count == 2){
                 //Destroy(GameObject.Find("Canvas"));
                 GameObject.Find ("myHazard").GetComponent<ObjectMover>().speed = 1f;
                 StartCoroutine(moveLogo());
                 Destroy(GameObject.Find ("PlayerStands"));
                 print ("destroy parent");
                 GameObject.Find("AudioManager").GetComponent<AudioSource>().Stop();
                 GameObject.Find("AudioManager").GetComponent<AudioSource>().Play();
                 //gameStart = false;
             }
         }catch(System.Exception){
             print ("caught exception");
             GameObject.Find ("myHazard").GetComponent<ObjectMover>().speed = 1f;
             StartCoroutine(moveLogo());
             //Destroy(GameObject.Find("Canvas"));
             Destroy(GameObject.Find ("PlayerStands"));
             //gameStart = false;
             GameObject.Find("AudioManager").GetComponent<AudioSource>().Stop();
             GameObject.Find("AudioManager").GetComponent<AudioSource>().Play();
         }
 
     }
 
     private IEnumerator moveLogo(){
         while(GameObject.Find("myHazard")){
             yield return null;
         }
         gameStart = false;
     }
 
     public GameObject[] GetPlayers(){
         print ("Dictionary Count : " + playerRepresentations.Count);
         GameObject[] returnedArray = new GameObject[playerRepresentations.Values.Count];
         List<GameObject> playerReps = new List<GameObject> (playerRepresentations.Values);
         int i = 0;
         foreach (GameObject player in playerReps) {
             returnedArray[i] = player;
             i++;
             try{
             //print("index:"+ i + " " + player.gameObject.name);
             }catch{/*print(i + " player gone at this index");*/}
         }
         return returnedArray;
     }
 
     public void setCanUseAbility(bool newValue){
         canUseAbility = newValue;
     }
 }
 
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

0 Replies

· Add your reply
  • Sort: 

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

42 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

Related Questions

Invalid PBX project - iOS Build Help! 2 Answers

Exceptions in C# 0 Answers

Problem with Lists and Remove 0 Answers

IndexOutOfRangeException: Array index is out of range / EnemiesSpawner.cs:18) 3 Answers

Cannot set parent for instantiated GameObject. (Exception: Can't destroy Transform component of...) 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