Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Values

Discussion in 'Scripting' started by Lineout, Nov 13, 2015.

  1. Lineout

    Lineout

    Joined:
    Jul 31, 2015
    Posts:
    10
    Is there a way to store a value inside of a game object and access that value via script? If not, what is the best way to go about something like this?
     
  2. ehdeekay

    ehdeekay

    Joined:
    Nov 9, 2012
    Posts:
    18
    You can have a script that has values of Float, Int, String and you can access it from another GameObject or Script.

    Script 1:

    Code (csharp):
    1. public float myFloat = 1f;
    2. public int myInt = 1;
    3. public string myString = "This is my string";
    If you have another script and you know the GameObject you can either reference it via public declaration or just Find the GameObject.

    Code (csharp):
    1. GameObject.Find("MyObject").GetComponent<MyValueScript>().myFloat = 2f;
    2. GameObject.Find("MyObject").GetComponent<MyValueScript>().myInt = 1;
    3. GameObject.Find("MyObject").GetComponent<MyValueScript>().myString = "This is my new updated string";
    Those values are updated and stored for the duration of the applications run-time.

    Saving those and loading them in another instance is a whole other objective.