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 :wink:

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*.State == true)*

{
MyList*.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!”);
}
}

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*.State == true)*
  •  {*
    

_ MyList*.State = false;*_
MyList .myParent.ChangeBools (MyList );

* 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.