非常简单的问题:在C#(Unity)中,我创建了一个新的自定义类,从附上的Monobehaviour类:
CustomClass test1 = new CustomClass(t1, t2, 0.5f);
我希望这个班级实例知道它的创造者是谁 - 这是一个coroutine,应该检查其父母是否被销毁。我当然可以这样通过:
CustomClass test1 = new CustomClass(this, t1, t2, 0.5f);
///
CustomClass(MonoBehaviour creator, string t, string t2, float a);
但是,是否有一种更优雅的(=自动)方法可以做到这一点?我知道静态功能的以下方法:
public static void Test(this MonoBehaviour behaviour, float a);
///
this.Test(0.5f);
类构造器是否有类似的东西?
必须手动完成。确实有 no 自动传递该参考的方法,但是有一种方法可以执行此操作而无需通过函数或构造函数。
您可以使用 static
字典来简化这一点。虽然,每次创建CustomClass
的新实例。
CustomClass
和MonoBehaviour
添加到字典中在CustomClass
函数中,您可以通过将CustomClass
实例传递到该 static
字典来从字典中检索MonoBehaviour
的函数。
类别创建CustomClass
类新实例的类的示例:
public class TestMono: MonoBehaviour
{
public static Dictionary<CustomClass, MonoBehaviour> classToMonoBehaviour;
// Use this for initialization
void Awake()
{
classToMonoBehaviour = new Dictionary<CustomClass, MonoBehaviour>();
//Create and add class to the dictionary
CustomClass cclas = new CustomClass();
classToMonoBehaviour.Add(cclas, this);
}
}
需要访问创建它的MonoBehaviour
的CustomClass
类:
public class CustomClass
{
public CustomClass(){}
public MonoBehaviour getCreator()
{
//Access MonoBehaviour from the dictionary
MonoBehaviour result;
TestMono.classToMonoBehaviour.TryGetValue(this, out result);
return result;
}
}