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

Changing Value Of A Property Without Knowing The Component Its In

Discussion in 'Scripting' started by CyanLichenstar, Apr 12, 2019.

  1. CyanLichenstar

    CyanLichenstar

    Joined:
    Oct 16, 2018
    Posts:
    2
    So I have a string called BoolName, for the purpose of this BoolName = DoAction: OpenDoor[true]

    What i want to do with the string is:
    - remove the DoAction: part (done this)
    - figure out if the [true] part says true or false then remove it (done this)
    - take the remaing bit that says "OpenDoor" and use it to find the bool property in an unknown script called OpenDoor

    Heres the code I have so far:
    `
    public void PerformAction()
    {
    BoolName = System.Convert.ToString(DialogueValue.Remove(0, 11)); // This bit is just removing the "DoAction:" part that will always be at the start

    if (BoolName.Contains("[true]"))
    {
    Debug.Log("String contains true");
    BoolName.Replace("[true]", string.Empty); // Removing the true/false part to just leave the name of the bool being targeted

    SetBoolToTrue(BoolName);
    }

    else if (BoolName.Contains("[false]"))
    {
    Debug.Log("String contains false");
    BoolName.Replace("[false]", string.Empty); // Removing the true/false part to just leave the name of the bool being targeted
    }
    }`
     
  2. GroZZleR

    GroZZleR

    Joined:
    Feb 1, 2015
    Posts:
    3,201
    If you have a limited set of actions, just hard code the potential outcomes. When you parse "OpenDoor", then call GetComponent<Door>() and call Open() on it. If you have a huge suite of actions, you're going to need something more intelligent.

    One potential middleground solution is to create an interface, say IScriptable, that exposes an OnAction(string) method. Implement the interface to your Door component that only reacts to "Open" and "Close" commands. You can then implement the interface on any other "scriptable" components so that they only react to their own commands. This will help keep things a bit more self-contained.
     
  3. image28

    image28

    Joined:
    Jul 17, 2013
    Posts:
    457
    You could store the bool as string/int/float as a Player Preference and look it up from anywhere in the game.

    Good way to configure the user interface is with generic template functions for looking up strings/int/floats (MusicVolume, SoundVolume, etc. )