c# - 如何更改父元素的子属性?
问题描述
我正在制作简单的游戏,但我不知道如何在代码中更改颜色。我有父游戏对象,我计划在其中附加脚本以更改子元素颜色。
例如我有这个:
Parent:A
Childs in A = 1,2;
我想获取所有 2 个元素并将第一个子元素的颜色更改为黑色,第二个子元素更改为白色。
我想在更改颜色时更改标签,这样我就可以在孩子身上实现随机颜色。
我不知道我怎样才能让那个父母的 2 个孩子改变财产。
我可以将孩子命名为 1 和 2,然后从代码中查找具有游戏对象名称 1 的孩子并更改颜色属性,如果可以的话,我该怎么做?
解决方案
以下代码部分是 GetProperty 方法的快速示例用法。只需使用 MyGetProperty 和 MySetProperty,如下所示。请记住,字符串将引用的变量必须是属性。
public class Parent {
private int child1 = 0;
private int child2 = 0;
public int iChild1 {
get {
return child1;
}
set {
child1 = value;
}
}
public int iChild2 {
get {
return child2;
}
set {
child2 = value;
}
}
public void MainMethod() {
MySetProperty("iChild1",1);
MySetProperty("iChild2",2);
string strOutput = String.Format("iChild1 = {0} iChild2 = {1}",MyGetPrperty("iChild1"), MyGetPrperty("iChild2"));
}
public object MyGetProperty(string strPropName)
{
Type myType = typeof(Parent);
PropertyInfo myPropInfo = myType.GetProperty(strPropName);
return myPropInfo.GetValue(this, null);
}
public void MySetProperty(string strPropName, object value)
{
Type myType = typeof(Parent);
PropertyInfo myPropInfo = myType.GetProperty(strPropName);
myPropInfo.SetValue(this, value, null);
}
}
推荐阅读
- javascript - 无法让 JS 验证响应
- javascript - 如何使函数立即被调用,然后每 5000 毫秒调用一次
- javafx-8 - 从 ImageView 获取 id,如果 getId 然后与特定的 ImageView id 进行比较?
- text - 如何增加记事本++(v7.5)中的标签宽度?
- javascript - 卡住让 For Loop 在第一次迭代时正确执行
- foreach - 如何使用 For Each 循环但以相同的发送顺序获取 Request.Querystring 的名称/值?
- python - 在python中打开一个文件并使用里面的数据来创建多个变量
- visual-studio - Visual Studio 在键盘上运行缓慢、键盘滞后以及从键盘输入中随机复制击键
- linux - 如何使用 bash 写入除现有常规文件之外的任何文件?
- javascript - 如何使用本机元素访问嵌套的 shadow-dom Ionic 角度