• 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
3
Question by xandermacleod · Mar 31, 2014 at 05:11 PM · getcomponentsearch

GetComponent with multiple instances of same script on object

Hi there,

I was wondering if there was a way of identifying a specific script on a gameObject via one of it's variables. Here's my situation.

I have a gameObject in my scene called "Players".

Attached to this otherwise empty gameObject, I attach 4 copies of the same script called 'PlayerScript'. The function of Playerscript is to keep track on individual stats for each of the players in my game such as health, score etc. I don't want to have multiple scripts per player, or even scripts which inherit from one script. One of the variables in PlayerScript is a public int known as PlayerID. It is the only variable which acts as a unique identifier for each script.

When I use GetComponent in an example such as:

public GameObject playersObject; (assign in inspector) public PlayerScript exampleScript;

void Start(){ exampleScript = playersObject.GetComponent(); }

Can I do it in such a way that I can identify the specific script I want, such as the one with the PlayerID variable being equal to 3?

How might I go about doing this (aside from having multiple objects and 1 script per object)?

Comment
Add comment · Show 1
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 xandermacleod · Mar 31, 2014 at 05:13 PM 0
Share

ok i cant write out the getcomponent line properly for some reason )formatting i think). but you get the picture of what im asking i hope.... (that syntax bit isnt relevant)

1 Reply

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

Answer by Leuthil · Mar 31, 2014 at 05:28 PM

You can use GetComponents to get all of them and then loop through and detect which is which by the PlayerId.

 public GameObject playersObject;
 public PlayerScript exampleScript;
 
 void Start() {
     PlayerScript[] playerScripts = playersObject.GetComponents<PlayerScript>();
     foreach (PlayerScript playerScript in playerScripts) {
         if (playerScript.PlayerId == 3)
         {
             exampleScript = playerScript;
         }
     }
 }

But realistically that is pretty inefficient especially since you may be calling individual players often. I would suggest creating a Hashtable/Dictionary of PlayerScripts that is initialized on some other object's Start function (perhaps a GameManager script?) that has all of these scripts. Basically this Hashtable/Dictionary would associate each unique PlayerId to its appropriate PlayerScript.

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 xandermacleod · Mar 31, 2014 at 05:39 PM 0
Share

can you let me know a bit more about these hashtables. Ive never heard of em, and the link is broken.

avatar image Leuthil · Mar 31, 2014 at 06:03 PM 0
Share

Since you are using C# it's probably better you use a Dictionary which is a Hashtable except that it can enforce types which means you can tell it what data types you want it to store.

You will need to make sure you include the generic collections namespace otherwise Lists and Dictionaries won't be available and you will get errors. Here is some example code to get you started (based off the code in my original answer):

 // includes the namespace that has the Dictionary class
 using System.Collections.Generic;
 
 public GameObject playersObject;
 public PlayerScript exampleScript;
 // create a Dictionary with a key of type int and a value of type PlayerScript
 public Dictionary<int, PlayerScript> allPlayerScripts = new Dictionary<int, PlayerScript>();
  
 void Start() {
     // Get all the PlayerScripts on this GameObject
     PlayerScript[] playerScripts = playersObject.GetComponents<PlayerScript>();
     // Loop through all PlayerScripts and add an entry into the Dictionary
     // which allows us to store each PlayerScript for each unique PlayerId
     foreach (PlayerScript playerScript in playerScripts) {
         allPlayerScripts.Add(playerScript.PlayerId, playerScript);
         // or you could replace the above line with the line below
         // SetPlayer(playerScript);
     }
 }
 
 // Example function which can get a PlayerScript
 // for a certain PlayerId
 public PlayerScript GetPlayer(int playerId) {
     return allPlayerScripts[playerId];
 }
 
 // Example function which can set a PlayerScript
 // for a certain PlayerId. Uses the PlayerId
 // from the passed in PlayerScript
 public void SetPlayer(PlayerScript playerScript) {
     allPlayerScripts.Add(playerScript.PlayerId, playerScript);
 }

For more information, you can refer to the official documentation on the Dictionary class.

avatar image xandermacleod · Mar 31, 2014 at 06:21 PM 0
Share

cheers. you're a star

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

21 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

Related Questions

Passing a string from Javascript to C# 1 Answer

How to Remove Multiple Components of Same Type from Game Object? 2 Answers

AddComponent not working 3 Answers

GetComponent Errors 2 Answers

Updating GUIText 3 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