Example #1
0
    public GameObject CreateUnit(GameObject building, GameObject unit)
    {
        Spawner spawner = building.GetComponentOrEnd<Spawner>();

        spawner.initBounds();
        Vector3 spawningPoint = spawner.SpawningPoint;
        Vector3 rallyPoint = spawner.RallyPoint;

        Ray ray = new Ray(rallyPoint + new Vector3(0, 100, 0), -Vector3.up);

        bool freeSpaceFound = false;

        RaycastHit hitInfo = new RaycastHit();

        int multiplier = 2;

        while (!freeSpaceFound && Physics.Raycast(ray, out hitInfo))
        {
            if (hitInfo.collider.transform.tag == "Ground")
            {
                //Noone there

                bool someoneElse = false;
                foreach (Transform target in targetsParent.transform)
                {
                    if (target.position == hitInfo.point)
                        someoneElse = true;
                }

                if (someoneElse)
                {
                    ray.origin += Vector3.right * multiplier;
                    multiplier = (int)-Mathf.Sign(multiplier) * (Mathf.Abs(multiplier) + 2);

                }
                else
                {
                    freeSpaceFound = true;
                }
            }
            else
            {
                ray.origin += Vector3.right * multiplier;
                multiplier = (int)-Mathf.Sign(multiplier) * (Mathf.Abs(multiplier) + 2);
            }

        }

        if (freeSpaceFound)
        {

            GameObject newUnit = Instantiate(unit, spawner.SpawningPoint, Quaternion.identity) as GameObject;

            // Set unit as parent in hierarchy
            newUnit.transform.SetParent(unitsParent.transform);
            GameObject target = Instantiate(targetPrefab, spawner.RallyPoint, Quaternion.identity) as GameObject;

            target.transform.SetParent(targetsParent.transform);
            UnitMovement script = newUnit.GetComponent<UnitMovement>();
            if (script != null)
            {
                script.startMoving(target);
                target.GetComponent<timerDeath>().AddUnit(newUnit);
            }
            return newUnit;
        }
        else
        {
            return null;
        }
    }