Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Do variables from instanced classes not update their values from the inspector?

Discussion in 'Scripting' started by hades01, Jan 28, 2015.

  1. hades01

    hades01

    Joined:
    Feb 26, 2014
    Posts:
    4
    I'm quite new at this so I apologize if this is some triviality I've overlooked but I'm pretty much stuck.

    I have a public variable declared in class A, and I need to use it in both classes A and B. So my understanding is that, since neither class can be made static, I have to instantiate an instance of one class in the other. Okay, no problem, that works fine. It pulls the value and I can use it in the other class.

    However, when I adjust the value in the inspector, the inspector value only gets propagated through class A; class B is stuck on the initialized value.

    Did I make a mistake somewhere or is this just a characteristic of reading values from an instance? Is there any way to overcome this quandary such that the inspector value is used in both classes?

    Thanks in advance.
     
  2. Kiwasi

    Kiwasi

    Joined:
    Dec 5, 2013
    Posts:
    16,860
    Are you looking for a prefab?
     
  3. hades01

    hades01

    Joined:
    Feb 26, 2014
    Posts:
    4
    Script A is attached to a prefab, yes.

    I just noticed I get a compile warning:

    "You are trying to create a MonoBehaviour using the 'new' keyword. This is not allowed. MonoBehaviours can only be added using AddComponent(). Alternatively, your script can inherit from ScriptableObject or no base class at all
    UnityEngine.MonoBehaviour:.ctor()"

    So is the issue that Unity doesn't know which prefab I'm looking for? I only have one in the scene, but I suppose there's nothing preventing me from having more.
     
  4. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,520
    There is some "stickiness" to the state of variables of the editor. Lets say you have a script that declares a public variable like so:

    Code (csharp):
    1.  public int foo = 123;
    When you first hang that script on an object, you will see 123 in the inspector field.

    If you update the script to initialize with a new value, the value will not change in the inspector.

    Conversely, changing the value int he editor (obviously) does not change the value in the code.

    If you create a new instance of the script (with the new initial value), the second instance will have that new value.

    This stickiness also applies to prefabs, since those are essentially "editor snapshots."

    It can all be a bit confusing until you build a firm mental image of where each piece of data comes from: loaded out of the scene, loaded from a prefab, modified by the user in the editor, or initialized in the script itself.