Search Unity

Question How to get a variable value from another script(C#) without setting script name.

Discussion in 'Scripting' started by nebrE4002, Oct 28, 2022.

  1. nebrE4002

    nebrE4002

    Joined:
    Mar 21, 2022
    Posts:
    1
    I want to request a value from another script, I do this with these lines of code:
    Code (CSharp):
    1. public GameObject chooseGameObject;
    2.  
    3. void Update()
    4.     {
    5.         Debug.Log(chooseGameObject.GetComponent<scriptName>().value1);
    6.     }
    7.  
    I want to use this code for multiple scripts. the problem is that I have to adjust the scriptName for each script in the code. I wish you could enter the name of the script you want a value for in the Unity Inspector.

    something like this:
    Code (CSharp):
    1.  
    2.     public GameObject chooseGameObject;
    3.  
    4.     public string scripName;
    5.    
    6.     void Update()
    7.     {
    8.         Debug.Log(chooseGameObject.GetComponent<scripName>().value1);
    9.     }
    Is there an option to modify <scripName> to a string or something?

    thanks in advance.
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,686
    You need a fixed type to do GetComponent<T>().

    If you need a fixed type that works with many different scripts at the same time, look into interfaces.

    Each of the intended scripts would need to implement the interface and then you would GetComponent<T>() with the interface.

    Using Interfaces in Unity3D:

    https://forum.unity.com/threads/how...rereceiver-error-message.920801/#post-6028457

    https://forum.unity.com/threads/manager-classes.965609/#post-6286820

    Check Youtube for other tutorials about interfaces and working in Unity3D. It's a pretty powerful combination.
     
    SisusCo and Bunny83 like this.