Use input field value from other component in script

Hi,
I have a component “gearcontroller” with an attached script to add an input field to the editor:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class values : MonoBehaviour

{
    public string my_name;
}

Now I can enter text in the editor, which I would like to use in another script as “pname”

I believe using gameObject.GetComponent would be the way but I cannot figure out how to adress it:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;
...
string pname = gameObject.getComponent(values.my_name)

I found a lot of information on how to do this within a single script, but don’t find a solution for my case.

Thanks for your help!

Something like this:

string name = gameObject.GetComponent<values>().my_name;

Note that if your script is on the different gameobject, you might need to reference it instead “this” gameObject.

1 Like

You almost got it:

values myValuesScrip = this.gameObject.GetComponent<values>();
string pname = myValuesScript.my_Name;

Note that this will only work if both scripts are attached to the same GameObject. If not, you will need to Change the Access from “this.gameObject” to “otherGameobject”, and add a “public GameObject otherGameObject” to the script, and finally drag the object with the values component into the Slot in Editor.

1 Like

thanks, @csofranz

The scripts are attached to different levels of an object:
There is a canvas object which has the second script attached to it.
The first script is attached to one of multiple buttons which are nested to the canvas.

In this case, is this the same GameObject? I am getting a “NullReferenceException: Object reference not set to an instance of an object” error in the debugger. According to Unity - Manual: GameObjects it should be the same GameObject

before I am wasting everyones time, my goal is to have the first script which defines the parameters attached to all buttons with of course different values for my_name - is my approach feasible at all?

thanks again