Search Unity

Event from a runtime instatiate Prefab

Discussion in 'Scripting' started by Patrick_Rainer, Aug 20, 2019.

  1. Patrick_Rainer

    Patrick_Rainer

    Joined:
    Feb 26, 2018
    Posts:
    49
    Hello people

    I am having a problem to write some code.

    As you see in the diagram, I am having different classes. The "spawner class" instantiates "AnimalPrefabs" during runtime. Now the "Animal-Object" has an event, for which I want to "addlistnener" in the GuiOverlayController. To do this, I can't get the instatiated Animal as GameObject. Then the event will be unknown.

    How to get a typed object in the GuiOverlayController, from the instance?

    I hope it is understandable what I mean.

    Thank you for helping out.
    Patrick
     

    Attached Files:

  2. palex-nx

    palex-nx

    Joined:
    Jul 23, 2018
    Posts:
    1,748
    Code (CSharp):
    1. var animalObject = Instantiate(animalPrefab);
    2. if(animalObject  != null) {
    3.    var animal = animalObject.GetComponent<Animal>();
    4.    animal.someEvent.AddListener(ListenerFunc);
    5. }
     
    Patrick_Rainer likes this.
  3. Patrick_Rainer

    Patrick_Rainer

    Joined:
    Feb 26, 2018
    Posts:
    49
    Thats what I now did and it works. Does

    Did work in a bit a different way. Thank you.