Search Unity

Bug UnityEvents not working on instantiated prefabs that were loaded using Addressables

Discussion in 'Editor & General Support' started by Josethehedgehog, Aug 9, 2021.

  1. Josethehedgehog

    Josethehedgehog

    Joined:
    Jul 26, 2017
    Posts:
    2
    Hello everyone!

    I recently encountered this bug after changing my workflow to use Addressable Assets.

    I'm using the ScriptableObjects events from Ryan Hipple of the Unite 2017 talk
    (This one for the ones who don't know)

    with Unity version 2020.3.15f2 and Addressable Assets version 1.18.15, Android platform for Oculus Quest.

    The set-up I have is as follows

    A spawner object which loads the prefab from the addressable group, then I cache it to a variable and then I spawned it with the traditional Instantiate(), after it is instantiated, 5 seconds later fires an event (lets say OnObjectSpawned).

    The prefab is supposed to hear said event and execute a method (assigned in the inspector) which just prints a message to console. The thing is that it is not working, said method never executes unless I execute it myself by using "Response.Invoke()".

    But if I instantiate the prefab without using addressables (just by dragging it to the inspector and having it there as reference) the whole event system and method executing works as intended.


    For context I was Instantiating some prefabs that I had referenced in the inspector, but I just needed 1 active at all times so the other ones where loading into memory without needing them to, hence why I started using addressables to have only one loaded at the time.

    Here is the set-up (Addressables are built before I Build and Run to the device)

    The Spawner, loads the asset, instantiates it, 5 seconds later it fires OnObjectSpawned
    upload_2021-8-8_22-48-19.png

    The Addressable Prefab which is supposed to hear the event and then execute some logic (but it doesn't)
    upload_2021-8-8_22-53-0.png
     
  2. John_Leorid

    John_Leorid

    Joined:
    Nov 5, 2012
    Posts:
    650
    Yes because References to Assets break when creating Addressables.
    If you click on the ScriptableObject you have assigned, it won't highlight in the project view (or atleast, it shouldn't) because this isn't the ScriptableObject you have in your AssetDatabase but instead it is a copy. A clone.
    All references to such assets are packed into the Addressable. If the Addressable is loaded, those references are actually copies.

    So the reason why you don't get the event, is because you are sending it to the wrong ScriptableObject (or trying to receive it at the wrong one).

    So what can you do about it ... give the SO a unique ID and call the event in a static dicitionary instead.
    Or re-reference the ScriptableObject once the addressable is loaded. You need some way to work around the fact that you have a copy now and not the original SO anymore.