Search Unity

Question Question about Instatiate() inside a function called by a UnityEvent

Discussion in 'Scripting' started by TheMattHaze, Dec 16, 2020.

  1. TheMattHaze

    TheMattHaze

    Joined:
    Oct 9, 2018
    Posts:
    2
    (Unity version 2020.1.16f1 Personal)
    I really don't understand why, but it doesn't seem to work like i expect it to. Can anyone explain me why?

    This gives no Exceptions but does terminate the method call:
    Code (CSharp):
    1. using Assets.Scripts.http;
    2. using UnityEngine;
    3.  
    4. public class TrackList : MonoBehaviour
    5. {
    6.     public RectTransform Content;
    7.  
    8.     public GameObject TrackListEntryPrefab;
    9.  
    10.     public TrackRequest TrackRequest;
    11.  
    12.     private void Start()
    13.     {
    14.         TrackRequest.OnResult.AddListener(SpawnList);
    15.         TrackRequest.GetAllTracks();
    16.     }
    17.  
    18.     public void SpawnList() {
    19.         Instantiate(TrackListEntryPrefab, Content);
    20.     }
    21. }
    22.  
    But this does work (but it's ridiculous ofcourse):
    Code (CSharp):
    1. using Assets.Scripts.Model;
    2. using Assets.Scripts.http;
    3. using System.Collections.Generic;
    4. using System.Linq;
    5. using UnityEngine;
    6.  
    7. public class TrackList : MonoBehaviour
    8. {
    9.     public RectTransform Content;
    10.  
    11.     public GameObject TrackListEntryPrefab;
    12.  
    13.     public TrackRequest TrackRequest;
    14.  
    15.     private bool spawn = false;
    16.  
    17.     private void Start()
    18.     {
    19.         TrackRequest.OnResult.AddListener(SpawnList);
    20.         TrackRequest.GetAllTracks();
    21.     }
    22.  
    23.     private void Update()
    24.     {
    25.         if (spawn) {
    26.             AddEntry();
    27.             spawn = false;
    28.         }
    29.     }
    30.  
    31.     public void SpawnList() {
    32.         spawn = true;
    33.     }
    34.  
    35.     public void AddEntry() {
    36.         Instantiate(TrackListEntryPrefab, Content);
    37.     }
    38. }
     
  2. Antistone

    Antistone

    Joined:
    Feb 22, 2014
    Posts:
    2,836
    If your first posted solution failed but the second one worked, my guess would be that the event TrackRequest.OnResult is occurring on a different thread. Most UnityEngine functions are only safe to use on the main thread. Your second solution gets around this by setting a flag that is later processed by a function on the main thread.
     
  3. TheMattHaze

    TheMattHaze

    Joined:
    Oct 9, 2018
    Posts:
    2
    Ah i see. TrackRequest.OnResult is indeed invoked on a different thread! Thanks for the info you saved me a lot more headache.