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 /
avatar image
0
Question by paezrice · May 27, 2018 at 05:39 PM · arraylistprogramminginverse

How to get the name of a List from one of its items

So I got two Lists<> of GameObjects and i got a Method i want to pass one of those lists depending on which GameObject made the call to the method. Maybe some code might explain it a little easier:

 List<GameObject> playerList1 = new List<GameObject>(4);
 List<GameObject> playerList2 = new List<GameObject>(4);
 
 public void SwitchPlayerSelection(List<GameObject> playerList){
     foreach(player in playerList){
         if(player.isSelected) player.isSelected = false;
     }
     this.isSelected = true;
 }

So if some other script is calling this method when manipulating a playerobject, I want to be able to deselect all playerobjects from the list the calling playerobject belongs to, and just select the one calling it ( this ). But how do I find out, which List it DOES belong to? Here's an example:

     //imaginary method GET_LIST_NAME
     if(myPlayerObject.needsToBeSelected){
         myPlayerObject.SwitchPlayerSelection(myPlayerObject.GET_LIST_NAME())
     }

Note that i DO have workarounds for this (like checking both lists with List.Contains() and then looping through the appropriate one, or just use a Dictionary in the first place. But I'm curious if there is a feature of C#'s Lists (or arrays!!!) that allows me to conclude the list's name from one of its items. Thanks in advance.

Comment
Add comment · Show 3
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 Tobychappell · May 27, 2018 at 06:38 PM 0
Share

as in the variable name?

avatar image paezrice Tobychappell · May 27, 2018 at 11:17 PM 0
Share

yep, but as ImpOfThePerverse mentioned, it's probably impossible. It makes sense that there's no additional meta-data attached to objects in a list after all.

avatar image ImpOfThePerverse · May 27, 2018 at 07:07 PM 1
Share

It doesn't sound like that's possible: https://stackoverflow.com/questions/2064139/how-to-find-references-to-an-object-in-c-sharp Any number of lists and reference variables can point to a single object, so they're responsible for keeping track of the reference. The object itself is unaware of what's referencing it.

Your workaround with List.Contains() is probably the way to go.

1 Reply

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

Answer by QKlon · May 28, 2018 at 01:52 AM

Since any object - even int, float aso. - can become an item of a generic collection, there is no built-in to refer to the list(s), an object is listed in. Actually an object does not even know that it is referenced by a list. (There is only an internal reference counter used by garbage collection.) Further more c# lists do not have a name property like the UnityEngine.Object class. You have to implement it on your own. As you mentioned, the common 'workaround' is to lookup the possible lists. When using binary tree driven collections, the lookup time is acceptable even on larger numbers of items.

If you want more automatism and easier access, you can derive your own class from a collection of your choice and implement the corrosponding methods to your needs.

Here is a demo. Just copy it into a file 'ListedPlayer.cs', start play mode and read the console output. You can (and should in a productive environment) split it into multiple files.


ListedPlayer.cs

 using System.Collections.Generic;
 using UnityEngine;
 
 namespace Demo
 {
     public class ListedPlayer : MonoBehaviour
     {
       public string Membership
       {
         get
         {
           var rel = GetComponent<Relation>();
           return rel ? rel.BackRefToList.name : "none";
         } 
       }
     }
       
   
   
     public class Relation : MonoBehaviour
     {
       
       public BackRefItemList BackRefToList { get; private set; }
 
       
       // nested list class having access to private property
       public class BackRefItemList : List<GameObject>
       {
         public string name;
 
         //list constructors
         public BackRefItemList(string name = null)
         {
           setName(name);
         }
 
         public BackRefItemList(IEnumerable<GameObject> collection = null, string name = null) : base(collection)
         {
           setName(name);
         }
 
         public BackRefItemList(int capacity = 0, string name = null) : base(capacity)
         {
           setName(name);
         }
         
         
         private void setName(string name = null)
         {
           this.name = null == name ? "unnamed list" : name;
         }
 
         
         public void Add(GameObject gameObject)
         {
           base.Add(gameObject);
           Relation rel = gameObject.GetComponent<Relation>();
           if(!rel)
           {
             rel = gameObject.AddComponent<Relation>();
             rel.BackRefToList = this;
             return;
           }
           
           if(rel.BackRefToList != this)
           { 
             rel.BackRefToList.Remove(gameObject);
             rel.BackRefToList = this;
           }
         }
       }
     }
 
   
   
     public static class Global
     {
       public static Relation.BackRefItemList PlayerList1 = new Relation.BackRefItemList("Team 1");
       public static Relation.BackRefItemList PlayerList2 = new Relation.BackRefItemList("Team 2");
       
       public static GameObject[] players = new GameObject[8]; 
         
       [RuntimeInitializeOnLoadMethod]
       public static void testPlayList()
       {
         // init
         for(var i = 0; i<8; i++)
           (i<4 ? PlayerList1 : PlayerList2).Add(players[i] = new GameObject("Player "+i, typeof(ListedPlayer)));
           
         doTestOutputs("initialized player list");
         
         // let 2 players of team 1 join to team 2
         PlayerList2.Add(players[0]);
         PlayerList2.Add(players[1]);
         
         doTestOutputs("modified teams");
       }
       
       public static void doTestOutputs(string header)
       {
         Debug.Log("<b>"+header+"</b>");
         for(var i = 0; i<8; i++)
         {
           var p = players[i];
           Debug.Log("'" + p.name + "' is member of team '" + p.GetComponent<ListedPlayer>().Membership + "':");
         }
 
         foreach (var team in new[]{PlayerList1, PlayerList2})
         {
           Debug.Log("<b>Teammembers '" + team.name + "':</b>");
           foreach (var teamPlayer in team)
             Debug.Log(teamPlayer.GetComponent<ListedPlayer>().name);
         }
       }
     }
 }

Comment
Add comment · Show 1 · 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 paezrice · May 28, 2018 at 10:41 PM 0
Share

Thank you very very much for this detailed and useful answer!

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

111 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

Related Questions

Multiple Cars not working 1 Answer

Reference all objects inside of an Array or List? 2 Answers

A node in a childnode? 1 Answer

Filling array with Scribtable Objects automaticly? 1 Answer

C#: Array question, check value 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