【问题标题】:How to change child property of parent elements?如何更改父元素的子属性?
【发布时间】:2019-07-02 20:07:39
【问题描述】:

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

例如我有这个:

Parent:A
Childs in A = 1,2;

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

我想在更改颜色时更改标签,以便获得随机颜色 在孩子身上。

我不知道如何让该父母中的 2 个孩子改变财产。

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

【问题讨论】:

  • Child C = gameObject.GetComponent(typeof(Child)) as Child; 有帮助吗?
  • 好的,你可以通过查看转换来获取孩子,并通过一些检查,你可以使用transform.GetChild(n);获取第一个孩子,或者GetComponentsInChildren<class you need>();然后设置属性跨度>

标签: c# unity3d game-development


【解决方案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);
        }

    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-21
    • 2022-11-26
    • 1970-01-01
    • 2015-04-25
    相关资源
    最近更新 更多