Not changing value after being set.

Hello,

So, my problem is this:
I am accessing a variable from another script, the player can change that variable by input, the problem is for example,
I have a class A and anothee one called B, A contains a variable X, B accesse’s X from A using, I want B to keep the initial X variable even if it changes in A, is it possible?

public class A : MonoBehaviour {
    
    public GameObject X;

    OnMouseDown() {
    X = gameObject;
   }

    
    }




public class B : MonoBehaviour {
GameObject x;

void update
{
 GameObject A0 = GameObject.Find("A's GameObject");
        A a = A0.GetComponent<A>();
x=a.X
//Do something with x
        }
}

Hello there,

The way you do it here will always return the CURRENT value of X, not the initial one.

What you want to do instead is have a variable on B (let’s call it “initialX”), that gets assigned to X on Start().

Then, as long as you don’t change it, that initialX will always be the value that X had at the beginning.

private GameObject initialX = null;

private void Start()
{
   GameObject Aobject = GameObject.Find("A's GameObject");
   initialX = Aobject.GetComponent<A>().X;
}

Hope that helps!

Cheers,

~LegendBacon

@II_Spoon_II
So basically a simple script like that should work. If x is not set already then it will be set otherwise it will remain the same and because you set x in the other script before setting in in the original script then you will surely have the value you need.

public class A : MonoBehaviour {
     
    public GameObject X;
    private B other;
    
    void Start() {
        other = GetComponent<B>();
    }

    void OnMouseDown()
    {
        other.UpdateX(gameObject);
        X = gameObject;
    }
     
}
 
 
 public class B : MonoBehaviour {
      public GameObject x;
      private bool xRecieved = false;
      public void UpdateX(GameObject obj)
      {
           if (xRecieved == false) {
               x = obj;
               xRecieved = true;
           }
      }
 }

Since a GameObject is a reference type, the only solution is to have two fields.

public class A : MonoBehaviour
{
     private GameObject x ;
     public GameObject InitialX
     {
          get ; private set ;
      }

     void OnMouseDown()
     {
         x = gameObject;
         if( InitialX == null ) InitialX = gameObject ;
     }      
 }

 public class B : MonoBehaviour
{
    GameObject x;
 
     void Update()
     {
          // The following is **not advised at all**
          // Calling Find and GetComponent every frame is resources-consuming
          GameObject A0 = GameObject.Find("A's GameObject");
          A a = A0.GetComponent<A>();
          x = a.InitialX ;
          //Do something with x
      }
 }