Search Unity

  1. Unity 2020.2 has been released.
    Dismiss Notice
  2. Good news ✨ We have more Unite Now videos available for you to watch on-demand! Come check them out and ask our experts any questions!
    Dismiss Notice

AddComponent via EditorScript, then get null UnityEvent on the first time

Discussion in 'Scripting' started by Threeyes, Dec 26, 2019.

  1. Threeyes

    Threeyes

    Joined:
    Jun 19, 2014
    Posts:
    32
    Hi, When I Create a GameObject("GO"), and then add a Component Instance (which contains UnityEvent) using ContextMenu, the event property will be null for the first time. but after I select the new GameObject on Scene, it will be fine, is there any update function that I need to invoke? Here's the scripts:

    Code (CSharp):
    1. using UnityEngine;
    2.  
    3. public class Test : MonoBehaviour
    4. {
    5.     [ContextMenu("AutoSet")]
    6.     void AutoSet()
    7.     {
    8.         GameObject go = GameObject.Find("GO");
    9.  
    10.         if (!go)
    11.             go = new GameObject("GO");
    12.  
    13.         CustomComponent cc = go.GetComponent<CustomComponent>();
    14.         if (!cc)
    15.             cc = go.AddComponent<CustomComponent>();
    16.         Debug.Log(cc.unityEvent == null);//Log true
    17.     }
    18.  
    19. }
    20.  
    Code (CSharp):
    1. using UnityEngine;
    2. using UnityEngine.Events;
    3.  
    4. public class CustomComponent : MonoBehaviour
    5. {
    6.     public UnityEvent unityEvent;
    7. }
    by the way, I tried the following Script, no luck:(:
    • UnityEditor.SceneManagement.EditorSceneManager.MarkSceneDirty(UnityEditor.SceneManagement.EditorSceneManager.GetActiveScene());
    • SceneView.lastActiveSceneView.Repaint();
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    11,085
    What happens if you enable/disable the new component after adding it? Does that maybe trigger it?

    Code (csharp):
    1. cc.enabled = false;
    2. cc.enabled = true;
    I think you're operating on the edge of the editor/runtime/editor script serialization boundary (in terms of what the editor does for you at add-component time) and I'm sure there's some kind of workaround. It might be that you need a custom codelet in Awake() if the above doesn't work...
     
  3. Billy4184

    Billy4184

    Joined:
    Jul 7, 2014
    Posts:
    5,541
    See my solution here.
     
unityunity