Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 14 Next capture
2021 2022 2023
2 captures
13 Jun 22 - 14 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
3
Question by poxa · Oct 02, 2014 at 11:55 PM · gameobjectvariablegetcomponentstring

GetComponent() - Is it possible to pass a string variable as name of the script?

Newbie here, with excuses in advance if it was already answered or explained in some documents. Evidently I can't get it, even after reading severals posts and API's GetComponent() manual pages, I've solved nothing and I'm now more confused.

I have different Gameobjects with scripts on them all named like Cube1_MyScript, Cube2_MyScript, and so on.

I would like to access scripts passing their names as string variable to GetComponent(), if feasible. Something like this:

     public class Test : MonoBehaviour {       
     
           public Myscript script;
     
           void Update() {  [cut]

             objectname = hit.collider.name;
             scriptname = objectname+"_MyScript"; // In order to have Cube1_MyScript
     
             script = GameObject.Find(objectname).GetComponent<scriptname>();
             script.MyVarBool = true;
     
             }

This code obiouvsly doesn't work, just like several other that I've wrote, unfortunately I can't figure out alone if there's any way to get over this.

Thanks in advance for pointing out any info or help - will be very appreciated.

Comment
Add comment · Show 4
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 Landern · Oct 03, 2014 at 01:05 PM 0
Share

@poxa, what differences do the Cube1_$$anonymous$$yScript, Cube2_$$anonymous$$yScript, etc have over one another? Are they the same with slight changes? Can you give an example of the two? Could they just be one class but each instance have unique properties to help you flesh out the differences?

avatar image Landern · Oct 03, 2014 at 01:42 PM 0
Share

Well, lets say you create a Cube prefab, that prefab has whatever 3d model/2d texture you use to display the cube on screen. It also has a script called CubeScript.cs attached to it as a component. All cubes share this in common. If you dynamically create your cube through code when needed, you'd instantiate the prefab, modify the fields/properties needed. If you build it all in the scene editor, you can hand modify none private fields(in c#) in unity's inspector pane. If you went the abstract route, you would be deriving from that class in other classes and perhaps choosing to override default methods from the abstract class for whatever reason, this would to some degree put you in the same spot. Another options are interfaces, which describe HAVE TO BE implemented (even if you just throw a NotImplementedException) methods/properties/events/indexers in each class that derive/inherit from the interface.

What it allows you do with regarding an interface is call any of the common methods/properties/events/indexers on the class by interface with different implementations in each class.

I think explaining your game a little, how it's structured would help take this a step further. The code you pasted seems like the normal instantiate route would work and modify the values needed for instance of the prefab or whatever.

avatar image Landern · Oct 03, 2014 at 01:52 PM 0
Share

$$anonymous$$ight i also suggest you take a gander at some design patterns for classes in c#, this may help you understand some methods of implementing more robust class structures in your own code.

avatar image poxa · Oct 05, 2014 at 12:31 PM 0
Share

Landern, your suggestions were very helpful, thank you. I solved approaching the whole thing with an abstract class as a starting design pattern. I would be glad to mark as correct answer your comment, if possible, but I don't know how to do it.

3 Replies

· Add your reply
  • Sort: 
avatar image
3

Answer by Spinnernicholas · Oct 03, 2014 at 12:17 AM

Check the docs.

The third listing for GetComponent is:

 Component GetComponent(string type);

Here is the example:

 using UnityEngine;
 using System.Collections;
 
 public class ExampleClass : MonoBehaviour {
     public HingeJoint hinge;
     void Example() {
         hinge = gameObject.GetComponent("HingeJoint") as HingeJoint;
         hinge.useSpring = false;
     }
 }

Comment
Add comment · Show 7 · 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 Spinnernicholas · Oct 03, 2014 at 12:19 AM 1
Share

The docs can save you a lot of time and effort if you learn how to read them.

avatar image Tepei · Oct 03, 2014 at 12:24 AM 0
Share

Sure ! But i think it's not what he want.. He want to acces différent script , or an script that the name is unknow ... I have search for that also and i don't find it also..

avatar image Spinnernicholas · Oct 03, 2014 at 04:04 PM 0
Share

$$anonymous$$Y_STRING_VARIABLE has to be the name of a Component or Script Type, not the name of the object. And GetComponent needs to be called on the object with the component.

     public HingeJoint hinge;
  
     $$anonymous$$Y_STRING_VARIABLE = "Collider";
  
     void Example() {
     hinge = hit.GetComponent($$anonymous$$Y_STRING_VARIABLE) as HingeJoint;
     hinge.useSpring = false;
  
 }
avatar image Spinnernicholas · Oct 03, 2014 at 04:09 PM 0
Share
 public class Test : $$anonymous$$onoBehaviour {       
  
       public $$anonymous$$yscript script;
  
       void Update() {
  
         [cut]
  
         objectname = hit.collider.name;
         scriptname = objectname+"_$$anonymous$$yScript"; // In order to have Cube1_$$anonymous$$yScript
  
         script = GameObject.Find(objectname).GetComponent(scriptname);
         script.$$anonymous$$yVarBool = true;
  
         }
avatar image poxa · Oct 05, 2014 at 12:33 PM 1
Share

I've already read the related API docs as stated in the initial question. The code above doesn't work.

Show more comments
avatar image
3

Answer by Rispat-Momit · Mar 14, 2017 at 11:27 PM

After spending a few hours searching, I found the solution. Here is a small script that I made :)

This will create an array of Strings where you can write the names of the scripts you want to activate.

 var MyScriptNames: String[];
 
     function Start(){
     
     for(var i : int = 0; i < MyScriptNames.Length; i++)
         {
          (gameObject.GetComponent(MyScriptNames[i]) as MonoBehaviour).enabled = true;
          } 
     }
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
avatar image
0

Answer by Griffo · Oct 03, 2014 at 01:52 PM

I asked a similar question some time ago HERE

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.

Follow this Question

Answers Answers and Comments

9 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

GameObject to Variable to GameObject and add string? 1 Answer

Create a variable on a GameObject for access via the Object without GetComponent() 1 Answer

updating a gameobject variable from another script attached to another object 3 Answers

get variable from a different game object 1 Answer

How can I use GameObject.Find with a string and a variable ? 2 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