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. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Find object that haven't yet spawned

Discussion in 'Scripting' started by Racm_Games, Dec 10, 2015.

  1. Racm_Games

    Racm_Games

    Joined:
    Sep 23, 2015
    Posts:
    19
    Hi everyone,

    Well the problem is basically that I am trying to access a component in a game object that isn't yet spawned in the game, so even though I don't get any error, the method is not working as I want.

    This is an example of what am doing:
    Code (CSharp):
    1. void Start()
    2. {
    3.     object = FindObjectOfType<Enemy>().GetComponent<Enemy>();
    4.  
    5.     object.OnDeath += OnEnemyDeath;
    6. }
    7.  
    8.  
    So to break it down more, I am getting the component from the game object and subscribing a method from the current class to an action of the other class, but since it is being called in the start method and this is called only at the beginning of the game, it won't work. (If I put this in the update method it will be called many times per frame and I don't want that)

    So is there a way to get the components of the objects that will be spawned later, and only call that line once?
     
  2. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,744
    For starters, you don't need the GetComponent - FindObjectOfType returns the Enemy component itself, not a GameObject containing it.

    It sounds like you want to make this event static and not tied to a particular Enemy object, I think.
    Code (csharp):
    1. //in Enemy.cs
    2. public static event Action OnEnemyDeathCallback;
    3.  
    4. void DeathFunction() {
    5. OnEnemyDeathCallback();
    6. }
    7. //anywhere else
    8. OnEnemyDeathCallback += SomeFunctionHere;
     
  3. Racm_Games

    Racm_Games

    Joined:
    Sep 23, 2015
    Posts:
    19
    Hey thanks for your help!, it was a good idea but then I realise I could just create a method on the other class and call it after certain event happen... thanks tho