- Home /
How to get the instance a field belongs to?
Hello,
I hope someone can help me with this. The key in the code below is in the MMethod contained in Program class. There I check the members of the list MyList and if I find a true value I run the code within the conditional. So if fore example C2.A is the first true element from the list, I want to run the method ChangeBools from the instance C2, if it is for example C1.B I want to run the method ChangeBools from the instance C1 and so on. And there's my cuestion... Is there any way to get the Instance a Field belongs to? Thanks ;)
Here the code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Program : MonoBehaviour {
private Class2 C1;
private Class2 C2;
private Class2 C3;
private List<Class1> MyList;
void Start () {
InitializeList();
}
public void InitializeList()
{
MyList = new List<Class1> { C2.A, C1.C, C1.B, C1.A, C3.A };
}
public void MMethod()
{
for (int i = 0; i < MyList.Count; i++)
{
if (MyList[i].State == true)
{
MyList[i].State = false;
//Here I want to call the Method ChangeBools of the instance
break;
}
}
}
}
public class Class1
{
public bool State;
public Class1(bool state)
{
State = state;
}
}
public class Class2
{
public Class1 A;
public Class1 B;
public Class1 C;
public Class2()
{
A = new Class1(true);
B = new Class1(true);
C = new Class1(true);
}
public void ChangeBools(Class1 changed)
{
Debug.Log("I'm running!");
}
}
Answer by TreyH · Dec 23, 2017 at 04:33 PM
Add a reference to the parent class on the child's construction:
public class Class1
{
public bool State;
public Class2 myParent;
public Class1 (Class2 parent, bool state)
{
myParent = parent;
State = state;
}
}
public class Class2
{
public Class1 A;
public Class1 B;
public Class1 C;
public Class2 ()
{
A = new Class1 (this, true);
B = new Class1 (this, true);
C = new Class1 (this, true);
}
// MMtethod
}
Then your function would become:
public void MMethod()
{
for (int i = 0; i < MyList.Count; i++)
{
if (MyList[i].State == true)
{
MyList[i].State = false;
MyList [i].myParent.ChangeBools (MyList [i]);
break;
}
}
}
edit: There's probably a cute way with Reflection to get other variables that are holding a reference, but it's probably not the way you want to go. in your example, each Class2 is mapped to a unique Class1 -- this may not always be the case. In my experience, assigning a reference to another class that is intended to act as a parent / manager is a straightforward and readable way to accomplish this.
Hey @TreyH thank you for your reply!
Exactly, each Class2 is mapped to a unique Class1. So I see your suggestion a great and simple way ;)
$$anonymous$$orning @jarechalde , if the answer seems to have solved your question, be sure to mark it as the correct answer so that this thread will be closed. :-)
Enjoy the holidays!