Search Unity

  1. Unity 2019.1 is now released.
    Dismiss Notice

Constructors and MonoBehaviour - using update()

Discussion in 'Scripting' started by Zavalichi, Oct 13, 2018.

  1. Zavalichi

    Zavalichi

    Joined:
    Oct 13, 2018
    Posts:
    157
    Hi guys,
    I need your help.

    I have two class: class TrafficSignalsManager : MonoBehaviour and TrafficSignalsSpawner : MonoBehaviour
    I want to spawn all my traffic lights and after this I want to send my intersersections (every intersection has traffic lights) to TrafficSignalsManager and to create a functionality for every traffic lights.

    The problem is: when I press the play button, my intersections variable is allways null.
    upload_2018-10-13_18-14-46.png
    Can you help me, please?
     
  2. xVergilx

    xVergilx

    Joined:
    Dec 22, 2014
    Posts:
    1,479
    It's not possible to instantiate MonoBehaviours using constructors. Unity's console should've notified you about that already.

    If you really want to instantiate it, you should create a new gameobject, and attach the component to it.
    Code (CSharp):
    1. GameObject obj = new GameObject("SomeName);
    2. YourComponent comp = obj.AddComponent<YourComponent>();
    3. comp.SetIntersections(something);
    Better approach is to have a prefab pre-made, with that manager attached to it.
    That way you could use Instantiate(...) and GetComponent<T> to obtain the reference from it.


    Note that there's a different (design) approach to what you're doing right now.
    I'll just leave it be. There's no fun in learning, when there's no learning involved.
     
    Last edited: Oct 13, 2018
  3. Zavalichi

    Zavalichi

    Joined:
    Oct 13, 2018
    Posts:
    157
    Yeah, but I want to send a list with GameObjects
    upload_2018-10-13_21-12-23.png