首页 > 解决方案 > 如何更改父元素的子属性?

问题描述

我正在制作简单的游戏,但我不知道如何在代码中更改颜色。我有父游戏对象,我计划在其中附加脚本以更改子元素颜色。

例如我有这个:

Parent:A
Childs in A = 1,2;

我想获取所有 2 个元素并将第一个子元素的颜色更改为黑色,第二个子元素更改为白色。

我想在更改颜色时更改标签,这样我就可以在孩子身上实现随机颜色。

我不知道我怎样才能让那个父母的 2 个孩子改变财产。

我可以将孩子命名为 1 和 2,然后从代码中查找具有游戏对象名称 1 的孩子并更改颜色属性,如果可以的话,我该怎么做?

标签: c#unity3dgame-development

解决方案


以下代码部分是 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);
        }

    }

推荐阅读