Search Unity

  1. Unity 2018.3 is now released.
    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. Want more efficiency in your development work? Sign up to receive weekly tech and creative know-how from Unity experts.
    Dismiss Notice
  4. Build games and experiences that can load instantly and without install. Explore the Project Tiny Preview today!
    Dismiss Notice
  5. Nominations have been announced for this years Unity Awards. Celebrate the wonderful projects made by your peers this year and get voting! Vote here!
    Dismiss Notice
  6. Want to provide direct feedback to the Unity team? Join the Unity Advisory Panel.
    Dismiss Notice
  7. Improve your Unity skills with a certified instructor in a private, interactive classroom. Watch the overview now.
    Dismiss Notice

Constructors and MonoBehaviour - using update()

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

  1. Zavalichi

    Zavalichi

    Joined:
    Oct 13, 2018
    Posts:
    52
    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:
    894
    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:
    52
    Yeah, but I want to send a list with GameObjects
    upload_2018-10-13_21-12-23.png