我使用以下代码购买切换矩阵:
int amount = 27;
string[] keywords = new string[amount];
bool kws[]= new bool[amount];
for(int i=0;i<amount;i++)
keywords[i]=""+i;
int columns = 7;
int rows = 4;
int index=0;
int y=30+30* index;
int x=0;
int element=0;
foreach(string kw in keywords){
element++;
if(kws [index] = GUI.Toggle (new Rect (x, y, 100, 30), kws [index], kw)){
Debug.Log("Selected: "+kw);
}
index++;
x+=100;
if(element>rows){
//Reset for the next row
x=0;
element=0;
y+=30;
}
}
但是当我点击切换时,另一个显示为已选中。它似乎是按块数计算的。我仍然无法弄清楚这个缺陷在哪里,因为每个切换被分配给持有其状态的不同kws。
也许C#/ Unity wiz可以从数英里远的地方查明问题。
我想真正的问题是:
如何显示和跟踪一系列切换?
答案 0 :(得分:1)
以下是我的观点:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class NewBehaviourScript : MonoBehaviour
{
string[] keywords;
bool[] kws;
void Awake()
{
int amount = 27;
keywords = new string[amount];
kws = new bool[amount];
for (int i = 0; i < amount; i++) keywords[i] = "" + i;
}
void OnGUI()
{
int columns = 4;
int x, y;
for (int index = 0; index < keywords.Length; index++)
{
x = 100 * (index % columns);
y = 30 * (index / columns) + 30;
bool oldValue = kws[index];
kws[index] = GUI.Toggle(new Rect (x, y, 100, 30), kws[index], keywords[index]);
if (kws[index] != oldValue)
{
Debug.Log("Switched: " + keywords[index] + " to " + kws[index]);
}
}
}
}
最重要的是你应该将初始化和使用分开,因为在原始版本中,每次都会重置切换状态,按下按钮将不会产生持久影响。
其次,使用foreach循环只是跳过篮球以跟踪哪个bool随之而来是一个坏主意。如果关键字和kws数组真的是不可分割的,你可能想要创建一个包含字符串和bool的类或结构,以便它们始终在一起。我在这里展示的是下一个最好的东西。如果根据索引找到一个,则应该使用相同的索引来查找另一个索引。
最后我在那里放了一个经常看到的技巧来获得网格布局。网格中的位置再次完全由其索引驱动。你会经常看到%(modulo)和/(除法)一起使用。
答案 1 :(得分:0)
要告诉你要做什么有点难。也许是这样的?
const int amount = 27;
bool[] kws = new bool[amount];
void OnGUI()
{
string[] keywords = new string[amount];
for(int i=0;i<amount;i++)
keywords[i]=""+i;
int columns = 7;
int rows = 4;
int index=0;
int y=30+30* index;
int x=0;
int element=0;
foreach(string kw in keywords){
element++;
bool selected = GUI.Toggle (new Rect (x, y, 100, 30), kws [index], kw);
if(selected && !kws [index])
{
Debug.Log("Selected: "+kw);
}
kws[index] = selected;
index++;
x+=100;
if(element>rows){
//Reset for the next row
x=0;
element=0;
y+=30;
}
}
}