Search Unity

problem with class instantiate

Discussion in 'Scripting' started by Bolt, Jan 15, 2019.

  1. Bolt

    Bolt

    Joined:
    Dec 15, 2012
    Posts:
    296
    in my GameManager I have to instantiate enemies. I did a class that does not inherit from MonoBheaviur to be able to pass certain parameters.
    Code (csharp):
    1.  
    2.  Enemie enemie = new Enemie(startWaypoint.neighbors, gameObescr ,0.5f);
    3.         enemies.Add(enemie);
    4.  
    the parameters are: the route of waypoints that the enemy must travel, the game Object that figuratively represents the enemy, is the speed of walking. Below is the Enemy class:

    Code (csharp):
    1.  
    2. public class Enemie
    3. {
    4.     public List<Cell> waypoints;
    5.     public Transform enemie;
    6.     public float velocity;
    7.     public Enemie(List<Cell> waypoints, Transform enemie, float velocity)
    8.     {
    9.        
    10.         this.waypoints = waypoints;
    11.         this.enemie = enemie;
    12.         this.velocity = velocity;
    13.         enemie.transform.position = waypoints[0].floor.transform.position;
    14.        
    15.     }
    16. }
    17.  
    18.  
    This class has a coroutine function that I call in the previous script that is used to make it walk along the path. I noticed, however, that within this function I should call another coroutine but not inheriting from mono I can not do it. How could I do?
     
  2. SparrowGS

    SparrowGS

    Joined:
    Apr 6, 2017
    Posts:
    2,536
    Coroutines are a part of MB, no way around it.

    Do your coro in the manager, if you explain what your doing with said coro we can maybe give you another solution.
     
  3. dgoyette

    dgoyette

    Joined:
    Jul 1, 2016
    Posts:
    4,195
    There's really no reason to avoid using MonoBehaviour for your class. The "trick" to being able to pass initialization to it is pretty simple: Just deactivate the gameObject after instantiating it, set some values on the script, then enable the game object. For example:

    Code (CSharp):
    1. var theGameObject = Instantiate(prefab);
    2. theGameObject.SetActive(false);
    3.  
    4. var ctrl = theGameObject.GetComponent<MyController>();
    5.  
    6. // Set the values the script will need in its Start call.
    7. ctrl.InitialConfiguration(x, y, z);
    8.  
    9. // The script's "Start" method will be called some time after SetActive(true).
    10. theGameObject.SetActive(true);