Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Accessing Events Throwing Null Exception

Discussion in 'Scripting' started by helloxman, Oct 12, 2020.

  1. helloxman

    helloxman

    Joined:
    Oct 10, 2019
    Posts:
    13
    Hello I have a script accessing an instantiated game object of Vuforia from Hierarchy and adding a component to it:

    IEnumerable<TrackableBehaviour> tbs = TrackerManager.Instance.GetStateManager().GetTrackableBehaviours();

    foreach (TrackableBehaviour tb in tbs)
    {
    if (tb.TrackableName == "Fashion")
    {

    if (tb.name == "New Game Object")
    {

    // change generic name to include trackable name
    tb.gameObject.name = ++counter + "DynamicImageTarget-" + tb.TrackableName;

    // add additional script components for trackable
    tb.gameObject.AddComponent<DefaultTrackableEventHandler>();
    tb.gameObject.AddComponent<TurnOffBehaviour>();

    Up to here it is working but at this point/line when i try to add

    tb.gameObject.GetComponent<DefaultTrackableEventHandler>().OnTargetFound.AddListener(DressFound);

    is throwing null exception in runtime

    When I try

    tb.gameObject.GetComponent<DefaultTrackableEventHandler>().OnTargetFound.RemoveAllListeners();

    throwing null exception in runtime as well

    However when i try

    tb.gameObject.GetComponent<DefaultTrackableEventHandler>().enable = false;

    it is working and disabling script component


    void DressFound()
    {
    augmentation.SetActive(true);

    }

    Why i can't reach events on the script?
     
  2. helloxman

    helloxman

    Joined:
    Oct 10, 2019
    Posts:
    13
    I solved the issue with changing code in DefaultTrackableEventHandler script



    from



    public UnityEvent OnTargetFound;

    public UnityEvent OnTargetLost;



    to



    public UnityEvent OnTargetFound = new UnityEvent();

    public UnityEvent OnTargetLost = new UnityEvent();