Search Unity

How do you set the values of private fields for Monobehaviours created at runtime?

Discussion in 'Scripting' started by FBones, Dec 29, 2018.

  1. FBones

    FBones

    Joined:
    Aug 28, 2016
    Posts:
    73
    Simple question: If I have to create a MonoBehaviour component at runtime (either directly with AddComponent<MyClass>() or by instantiating a prefab), how can I set the value of private fields via script?

    If I were creating an instance of a normal class, I could set the values of the private field via a constructor. But using constructors to create monoBehaviours is considered poor practice.

    If the monoBehaviour were present at the start of the game, I could use [SerializeField] and set the value via the editor.

    Obviously, lots of initialization can be done via Start(), but there are lots of cases where the new object cannot automatically know the right value for its fields to have.

    For example, imagine I have a controller that is spawning a new gameObject that carries with it its own view and controller scripts (derived from MonoBehaviour). The controller that is spawning the new gameObject knows certain information that needs to be insinuated into private fields of the controller or view... information that the newly minted components cannot determine on their own. How to set these private or protected fields without using a constructor?
     
  2. You either make them public, since you want to modify them from another script or make a public setter or a public setter method.