动态地向游戏对象添加脚本并为其属性分配值 [英] Adding a script to a game object dynamically and assigning values to its properties
问题描述
我想向游戏对象添加脚本/组件并在该脚本中填充值.输入值来自父对象"LineManagerProperty".在下面的示例中,我想将"LineManager"类添加到"Line"游戏对象,并在"LineManager"中分配属性.如果您查看"Line"类,则添加"LineManagerProperty",以便它可以作为值传递到"LineManager"中,并出现在统一检查器中.有更好的方法吗?
I want to add a script/component to a game object and populate values in that script. The values for input come from the parent object as 'LineManagerProperty'. In the example below I want to add the 'LineManager' class to the 'Line' game object and assign the properties in 'LineManager'. If you look at the 'Line' class I add 'LineManagerProperty' so that it can appear in the unity inspector as values to pass into 'LineManager'. Is there a better way to do this?
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;
}
推荐答案
我不明白您想要什么,您是否想在检查器中看到LineManager,或者什么,但是我会尽力帮助.我猜您正在创建一些编辑器,而又不想将LineManager保存在预制件中.
I don't understand what you want, do you wanna see LineManager in inspector or not, or what, but i will try to help. I guess you are creating some editor and you don't want to save LineManager in prefab.
idk,也许它将为您提供一些想法.
Maybe it will give some idea for you, 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
}
}
这篇关于动态地向游戏对象添加脚本并为其属性分配值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!