Search Unity

Unity Event is null right after AddComponent

Discussion in 'Scripting' started by Billy4184, Jan 31, 2020.

  1. Billy4184

    Billy4184

    Joined:
    Jul 7, 2014
    Posts:
    6,025
    Hello, I'm looking to create a 'wizard' of sorts that adds components to a gameobject and connects various functions to Unity Events on those components.

    It seems that immediately after AddComponent, any Unity Event on the component is null, but at some later time becomes not null. Is that expected behaviour? Makes it a bit tedious if I have to wait some indeterminate amount of time before I can use the events.

    I also can't see any reason why the Unity Event would need to 'initialize' itself over some number of frames.
     
  2. Billy4184

    Billy4184

    Joined:
    Jul 7, 2014
    Posts:
    6,025
    After a bit of experimentation, I realized that Unity does not serialize components until they are clicked on and shown in an inspector.

    The answer was to (after calling AddComponent) create a new serialized object for it and call the Update method:

    Code (CSharp):
    1. MyComponent myComponent = myGameObject.AddComponent<MyComponent>();
    2. SerializedObject so = new SerializedObject(myComponent);
    3. so.Update();
    After which the unity event on the new component is no longer null.
     
    Threeyes and Maeslezo like this.
  3. etiennepinchon

    etiennepinchon

    Joined:
    May 16, 2018
    Posts:
    8
    Hey Billy, I have the exact same issue however "SerializedObject " is part of UnityEditor which means we cannot make a build with this. Did you find an alternative solution? Is this a bug that could be reported?
     
  4. Billy4184

    Billy4184

    Joined:
    Jul 7, 2014
    Posts:
    6,025
    I think you can just use 'new'.

    Code (CSharp):
    1. MyScript myScript = gameObject.AddComponent<MyScript>();
    2. myScript.myEvent = new UnityEvent();
    3. myScript.myEvent.AddListener(SomeFunction);
     
    Threeyes and agnis16 like this.