Search Unity

How to use UnityEventTools in script? "UnityEventTools is inaccessible due to its protection level"

Discussion in 'General Discussion' started by mikejm_, Nov 13, 2021.

  1. mikejm_

    mikejm_

    Joined:
    Oct 9, 2021
    Posts:
    346
    I am trying to use UnityEventTools.AddPersistentListener in some code attached to a game object. I added a new C# script:

    Code (csharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.UI;
    5. using UnityEngine.Events;
    6.  
    7. public class GenerateMenu : MonoBehaviour
    8. {
    9.     void MyFunction()
    10.     {
    11.         UnityEngine.Events.UnityEventTools.
    12.     }
    However at this point it gives me an error: "UnityEventTools is inaccessible due to its protection level"

    I am not really understanding how I can access AddPersistentListener. What am I doing wrong? Is it a namespace issue or do I need to inherit from a class or something? Can you please be very specific about how to solve this as I'm an amateur?

    Thanks.
     
  2. neginfinity

    neginfinity

    Joined:
    Jan 27, 2013
    Posts:
    13,563
  3. halley

    halley

    Joined:
    Aug 26, 2013
    Posts:
    2,420
    Thanks for the links.

    It's annoying that none of these reference pages have examples, and all the other examples I have seen didn't quite mention how to add listeners that are on other objects such as a different component. It is a bit misleading to see all the mentions of UnityAction here, too, because you really don't need to make some new object here, the plain old method reference works just fine.

    Code (CSharp):
    1.  
    2. myComponentInstance.myEvent = new UnityEvent();
    3. UnityEditor.Events.UnityEventTools.AddVoidPersistentListener(
    4.     myComponentInstance.myEvent, someOtherObjectInstance.theirMethod);
    5.