Is there a way to get the instance of the class that created the class?
For example I have the following example:
public class MyClass {
private GameObject initiator;
public MyClass(){
initiator = // Get the value here
}
}
This class then creates a new MyClass
and initiator
from above and stores the instance of MyInitiator
in initiator
.
public class MyInitiator : MonoBehaviour {
void Start() {
new MyClass();
}
}
I know that I can pass this
as a parameter or create a property and set it that way, but I would like to avoid having to do that, and have it do it automatically or with some sort of logic within MyClass
if possible.
I don't think there is any other way than the two you have suggested.
I would do it as a constructor parameter with this
and use a method to create a new instance, like so:
public class MyClass
{
private GameObject initiator;
public MyClass(GameObject initiator)
{
this.initiator = initiator;
}
}
public class MyInitiator : MonoBehaviour
{
void Start()
{
MyClass first = NewMyClass();
MyClass second = NewMyClass();
// ...
}
private MyClass NewMyClass()
{
return new MyClass(this);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.