动态地向游戏对象添加脚本并为其属性分配值

时间:2017-07-07 13:07:05

标签: c# unity3d

我想将一个脚本/组件添加到游戏对象中并填充该脚本中的值。输入值来自父对象' LineManagerProperty'。在下面的示例中,我想添加' LineManager'排到'线'游戏对象并在' LineManager'中分配属性。如果你看一下' Line'我要添加' LineManagerProperty'这样它就可以作为值传递给统一检查员进入“LineManager”。有更好的方法吗?

enter image description here

public class Line : MonoBehaviour
{
    //This is added here so that values can appear in inspector
    //These values will be passed into 'LineManager' when its created and added to 'Line' game object
    public LineManagerProperty LineManagerProperty;

    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            //Add the 'LineManager' script and assign its properties
            gameObject.AddComponent<LineManager>().LineManagerProperty = new LineManagerProperty()
            {
                CollisionTag = LineManagerProperty.CollisionTag,
                MaxTimeDuration = LineManagerProperty.MaxTimeDuration,
                NumberOfHits = LineManagerProperty.NumberOfHits,
                Health = LineManagerProperty.Health
            };
        }
    }
}

public class LineManager : MonoBehaviour
{
    public LineManagerProperty LineManagerProperty;

    //...
}

[Serializable]
public class LineManagerProperty
{
    public string CollisionTag;
    public float MaxTimeDuration;
    public float NumberOfHits;
}

2 个答案:

答案 0 :(得分:0)

您在Unity中提供脚本的任何公共变量都将显示在检查器中,并且可以从任何位置进行设置。在您的情况下,将变量从LineManagerProperty移动到LineManager脚本:

public class LineManager : MonoBehaviour
{
    public string CollisionTag;
    public float MaxTimeDuration;
    public float NumberOfHits;

    //...
}

然后设置变量,只需使用GameObject。

_line.CollisionTag = "";
_line.MaxTimeDuration = 0;
//.....

希望这有帮助!

答案 1 :(得分:0)

我不明白你想要什么,你是否想在检查员中看到LineManager,或者是什么,但我会尽力帮助你。我猜你正在创建一些编辑器而你不想在预制中保存LineManager。

也许它会给你一些想法,idk。

#define EDIT_MODE // if you delete this, code in EDIT_MODE fields will ignored and never compiled
using UnityEngine;
public class Line : MonoBehaviour {
    public LineManagerProperty lineManagerProperty;
#if EDIT_MODE
    LineManager lineManager;
#endif
    void Start() {
#if EDIT_MODE
        lineManager = new LineManager(lineManagerProperty);
#endif
    }

    void Update() {
#if EDIT_MODE
        lineManager.Update();// if you want to call something
#endif
    }
}

public class LineManager  {
   public LineManager(LineManagerProperty lmp) {
       LineManagerProperty = lmp;
   }

   public LineManagerProperty LineManagerProperty;

   public void Update() { // if you want to call something
   }
}