Home>

I want to create an escape game in Unity.
I would like to select an item from the list of items, circle the item in red, and flag it.

I investigated a lot and tried to write a code using toggles as a group.
I want to use multiple items, but what kind of code is okay?

Please tell me if there is any good way.
Please let me know if there are other codes that are easy to use.
Because I am an amateur,
Thank you.

Error message
Error message
Applicable source code

C #
Source code
`` `
[SerializeField]
Toggle toggle;

private bool doesHaveHammer;

void Start () {

toggle.onValueChanged.AddListener (changeToggleEvent);

var toggleActive = toggle.isOn;

toggle.isOn = false;
}
void Update () {

}
public void changeToggleEvent (bool isActive) {
if (isActive == true) {
doesHaveHammer = true;
} else {
doesHaveHammer = false;

}}

Tried

Please describe what you tried for the problem here.

Supplemental information (FW/tool version etc.)

Please provide more detailed information here.

  • Answer # 1

    I think there are various ways, but priority is given to ease of understanding.

    I think that there is only one item selected, so I will put an item ID with an int instead of an individual bool.
    (If you can select multiple items at the same time, use List<int>or arrange them)

    // Toggle array: Put in order of item ID
        public Toggle [] toggles;
        // Currently selected item (-1 if none are selected)
        // currently private but please change accordingly
        private int nowChiceItemId = -1;
        void Start () {
            foreach (Toggle item in toggles) {
                item.onValueChanged.AddListener (OnChange);
            }
        }
        // called when the toggle changes
        // (Note that isOn is set for matching the onValueChanged argument, but it is not actually used)
        public void OnChange (bool isOn) {
            // Temporary unselected state ……
            nowChiceItemId = -1;
            // Check all Toggle ...
            for (int i = 0;i<toggles.Length;i ++) {
                // If there is something on ...
                if (toggles [i] .isOn) {
                    // Get the ID (array index)
                    nowChiceItemId = i;
                }
            }
        }


    Attach these sources to one appropriate object in the scene.
    After that, put the prepared Toggle intogglesfrom the inspector so that it is in the order of the item ID.
    (Please adjust the Toggle object on the hierarchy so that a red frame is attached when it is on.)

    After that, refer to nowChiceItemId at the timing to determine which is being selected.
    IfnowChiceItemId == 0, "the item in array 0 (first) is being selected"
    IfnowChiceItemId == 1, "the first item in the array (second from the top) is being selected"
    IfnowChiceItemId == -1, "No item selected"
    It becomes.