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 wano987 · Jan 12, 2017 at 04:54 PM · getcomponentarraysstring

Is it possible: "getComponent<_array_element_$>"?

Am am new one in Unity C#, so probably my request is nonsence due to platform limitations. Also, please excuse my english, I fear it will contant mistakes.

I know about http://answers.unity3d.com/questions/406655/getcomponent-possible.html but it seems like it doesn't fit my needs (or I am too noob to understand how it does).

For some reasons I need to check GameObjects for some (nearly random) scripts and turn it on/off on raycast. But when I tried to use some kind of that - it was a failure. GetComponent just do not want to use string variable as component name. How may I do this?

Actual (non-workable) listing:

 using UnityEngine;
 using System.Collections;
 
 public class RaycastFunctionSwither : MonoBehaviour {
 
     public string components;
     public float distance;
     private string element;
 
     // Use this for initialization
     void Start () {
     
     }
     
     // Update is called once per frame
     void Update () {
         string subject;
         string old_subject;
 
         if (Input.GetKeyDown("e"))
         {//if user want to use it
             var hit = RaycastHit;
             var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
             if (Physics.Raycast(ray, hit, distance))
             {//raycast gives new object, so old became an old one
                 old_subject = subject;
                 subject = hit.collider.gameObject.name;
 
                 if (subject != old_subject)
                 {
                     foreach (var Element in components)
                     {//check and turn off
                         if (old_subject.GetComponent(Element))
                         {
                             old_subject.GetComponent<element>().enable = false;
                         }
                     }
                     if (subject != null)
                     {//если объект != старый объект И объект != null
                         foreach (string element in components)
                         {//check and turn on
                             if (subject.GetComponent<element>)
                             {
                                 subject.GetComponent<element>().enable = true;
                             }
                         }
                     }
                 }
             }
         }
         else if (Input.GetKeyUp("e"))
         {   //check and turn off
             foreach (var element in components)
             {//check and turn off
                 if (old_subject.GetComponent<element>)
                 {
                     old_subject.GetComponent<element>().enable = false;
                 }
             }
         }
     }
 }
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
1

Answer by Hellium · Jan 12, 2017 at 04:56 PM

UPDATED ANSWER

 using UnityEngine;
 using System.Collections;
 
 public class RaycastFunctionSwither : MonoBehaviour
 {
     public string[] componentNames;
     public float distance;
     private Collider lastTarget ;
 
     // Update is called once per frame
     void Update ()
     {
         if (Input.GetKeyDown(KeyCode.E))
         {
             Collider hitCollider ;
             RaycastHit hit ;
             Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
             if (Physics.Raycast(ray, hit, distance))
             {
                 hitCollider = hit.collider;
 
                 // Check if target is the same as the old one
                 if ( lastTarget.GetInstanceID() != hitCollider.GetInstanceID() )
                 {
                     EnableComponents( lastTarget.gameObject, false ) ;
                     EnableComponents( hitCollider.gameObject, true ) ;
                 }
             }
         }
         else if (Input.GetKeyUp(KeyCode.E) && lastTarget != null )
         {
             EnableComponents( lastTarget.gameObject, true ) ;
         }
     }
     
     private void EnableComponents( GameObject target, bool enable )
     {
         foreach (string name in componentNames)
         {
             MonoBehaviour monoBehaviour = target.GetComponent( name ) as MonoBehaviour ;
             if ( monoBehaviour != null )
                 monoBehaviour.enabled = enable ;
         }
     }
 }


Note : Be very careful with the leter case when adding the components name in the components array !


INITIAL ANSWER

First of all : components is not declared as an array

Then try to get the component using the string version of GetComponent :

 private void EnableComponents( GameObject target, bool enable )
 {
     foreach (var element in components)
     {
         MonoBehaviour monoBehaviour = target.GetComponent( element ) as MonoBehaviour ;
         if ( monoBehaviour != null )
                monoBehaviour.enabled = enable ;
     }
 }

Then :

      // [...]
      else if (Input.GetKeyUp("e"))
      {
          EnableComponents( old_subject, false ) ;
      }
Comment
Add comment · Show 2 · 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 wano987 · Jan 13, 2017 at 09:18 AM 0
Share

Please excuse my dumbness, may you explain where the place of the first listing? I am really scared of the C# logic.

I had added listing A into update() { after STRING declaration, lising B had replaced each FOREACH section.

Effect: 'if (Input.Get$$anonymous$$eyDown("e")) Name "Input.Get$$anonymous$$eyDown" is not available in current context'. (o_o) It's nonsence for me. I can't understand logic of this compiler.

PS: also it seems like the raycast code was damaged due to iterations, so it now fails too. Please, if you will try to check it - just place a dummy variables.

avatar image Hellium wano987 · Jan 13, 2017 at 08:34 PM 0
Share

@wano987 : Updated answer. I haven't tested the code, I don't even know if it compiles, but check it out. About your raycast problem, make sure the candidates targets have a collider (not set to trigger)

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

5 People are following this question.

avatar image avatar image avatar image avatar image avatar image

Related Questions

String Arrays in a function 0 Answers

Using a String to populate GetComponent 1 Answer

public string array controlled by an int in the inspector 1 Answer

Using Random.Range in an array only gives a random output once 2 Answers

How do I convert Component[] array into String[] with GetComponentsInChildren? 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