Search Unity

  1. Improved Prefab workflow (includes Nested Prefabs!), 2D isometric Tilemap and more! Get the 2018.3 Beta now.
    Dismiss Notice
  2. The Unity Pro & Visual Studio Professional Bundle gives you the tools you need to develop faster & collaborate more efficiently. Learn more.
    Dismiss Notice
  3. Let us know a bit about your interests, and if you'd like to become more directly involved. Take our survey!
    Dismiss Notice
  4. Improve your Unity skills with a certified instructor in a private, interactive classroom. Watch the overview now.
    Dismiss Notice
  5. Want to see the most recent patch releases? Take a peek at the patch release page.
    Dismiss Notice

Constructors and MonoBehaviour - using update()

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

  1. Zavalichi

    Zavalichi

    Joined:
    Oct 13, 2018
    Posts:
    9
    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. VergilUa

    VergilUa

    Joined:
    Dec 22, 2014
    Posts:
    751
    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:
    9
    Yeah, but I want to send a list with GameObjects
    upload_2018-10-13_21-12-23.png