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

Question Mono Behavior in List

Discussion in 'Scripting' started by ChingissKI, Aug 31, 2023.

  1. ChingissKI

    ChingissKI

    Joined:
    Jun 5, 2022
    Posts:
    3
    I don't understand. It uses MonoBehavior as the data type in the list and puts null in it????

    How to find out then how many objects are in the List and what does it depend on??? And what does null do here? I don't know c# well

     
  2. ChingissKI

    ChingissKI

    Joined:
    Jun 5, 2022
    Posts:
    3
    rger
     

    Attached Files:

  3. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    5,846
    Should you not just be assigning to
    CachedInteractions
    , and not
    Interactions
    ?
     
    Bunny83 likes this.
  4. ChingissKI

    ChingissKI

    Joined:
    Jun 5, 2022
    Posts:
    3
    This is not my script. I just don't understand what happend, when we make MonoBehavior in <List> as a data type
     
  5. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    5,846
    List<T>
    is a reference type. Ergo, the field is just a pointer, or reference, to the actual object stored somewhere in memory. Like all reference types, it can be 'null' in that it points to nothing.
     
    AngryProgrammer and Bunny83 like this.
  6. Bunny83

    Bunny83

    Joined:
    Oct 18, 2010
    Posts:
    3,524
    Like Spiney said, the code should actually assign the new List to the "CachedInteractions" variable as it's not possible to assign it to a read-only property.

    This is essentially a lazy initialized property. The actual variable CachedInteractions is protected and set to null. When the Interactions property is used for the first time (in that case "CachedInteractions" is null) the getter of the property will create and fill the list with all components on the same gameobject that match a certain type (this is still missing in the shot you've shown).

    If this is a tutorial that you're following and they don't explain the "why", it's a bad tutorial.
     
    spiney199 and AngryProgrammer like this.
  7. AngryProgrammer

    AngryProgrammer

    Joined:
    Jun 4, 2019
    Posts:
    435
    It just looks like an overcomplicated idea. In Unity, if you want to cache you use ScriptableObjects (derived class like MonoBehaviour). Next, you can make many copies of such type that work like any asset, so you can drag and drop it in the place you need.