【发布时间】:2021-09-22 18:09:31
【问题描述】:
我有一个自定义类,我想在自定义编辑器中进行初始化。但是,由于某种奇怪的原因,构造函数返回 null!
编辑:是的,在 Unity 中,这是可能的。
这是一个例子:https://answers.unity.com/questions/1250722/why-do-constructors-return-null-when-used-within-e.html
另外,如果我没有使用正确的术语,我很抱歉(构造函数不会返回,感谢您指出这一点),但我仍然认为这个问题是可以理解的。
这里是抛出异常的代码:
[CustomEditor(typeof(ComponentMasterBase), true)]
public class ComponentMasterEditor : Editor
{
public override void OnInspectorGUI()
{
ComponentMasterBase cmb = (ComponentMasterBase)target;
//unrelated stuff here
if(GUILayout.Button("Add " + cmb.GetComponentType().DisplayName + " Slot"))
{
var c = new ComponentSlot(1, null, cmb.GetComponentType(), cmb);
Debug.Log(c); //Output: null
cmb.AttachComponentSlot(c); //Throws NullReferenceException
}
}
}
这是(稍微简化的)类:
public sealed class ComponentSlot : MonoBehaviour
{
#region Size
public static int MaximumSize = 6;
private int _size = 1;
public int Size
{
get { return _size; }
set
{
int prevSize = _size;
if (value > 0)
{
if (value <= MaximumSize)
_size = value;
else
_size = MaximumSize;
}
else
_size = 1;
if(prevSize != _size)
this.name = "Size " + _size + " " + ComponentType.DisplayName + " Slot";
}
}
#endregion
#region Component
private ShipComponent component;
public void SetComponent(ShipComponent c)
{
if (c == component) return;
if (c == null) return; //This should return out of the function, so no parenting stuff going on
if(component != null)
DestroyImmediate(component);
component = c;
c.transform.SetParent(this.transform);
}
public void UpdateComponent(){}
public ShipComponent RetrieveComponent(){}
public void DetachComponent(){}
#endregion
public ComponentTypes ComponentType;
public ComponentMasterBase Owner;
// 1 null eg ComponentTypes.Weapon caller
public ComponentSlot(int size, ShipComponent com, ComponentTypes t, ComponentMasterBase master)
{
Size = size; SetComponent(com); ComponentType = t; Owner = master;
Debug.Log("Created new weapon slot."); // This is printed.
}
public ComponentSlot() {}
}
我不知道我提供的代码是足够还是太多,因为我不知道问题出在哪里。我从来没有听说过一个不可为空的类型构造函数返回 null :(
【问题讨论】:
-
" 构造函数返回 null!"构造函数不能返回任何东西。请问有什么问题?
-
构造函数不能在 .NET 中“返回 null”。我怀疑您继承的
ToString方法正在返回 null。 -
没有。请阅读我的问题。对象为空。我稍后检查它。是的,构造函数返回一个对象。
-
此外,Unity 中对象的构造函数返回 null 的其他情况,因为它以某种方式连接到后面的 c++。这里:answers.unity.com/questions/1250722/…
-
@JakobTinhofer 构造函数是 public ComponentSlot(...) 它不能返回任何东西。有什么问题?