2

I am working on a football game project. I want a sphere I have to spawn another sphere after I throw the 1st sphere. Here's something I tried:

public class spawn : MonoBehaviour {
    public Transform[] SpawnPoints;
    public float SpawnTime;
    public GameObject ball;

    // Use this for initialization
    void Start () {
        InvokeRepeating ("SpawnBalls", SpawnTime, SpawnTime);
    }

    void SpawnBalls(){
        if (transform.position.z > -0.904 ) {
            int SpawnIndex = Random.Range (0, SpawnPoints.Length);
            Instantiate (ball, SpawnPoints [SpawnIndex].position, SpawnPoints [SpawnIndex].rotation);
        }
    }
} 
yummypasta
  • 1,398
  • 2
  • 17
  • 36
alter ego
  • 69
  • 7

1 Answers1

3

Simply instantiate a new ball if the last ball thrown is far enough. Try this:

public class spawn : MonoBehaviour {
    public Transform[] SpawnPoints;
    public GameObject ball;
    public GameObject lastBall;

    // Use this for initialization
    void Start () {
        int SpawnIndex = Random.Range (0, SpawnPoints.Length);
        lastBall = Instantiate (ball, SpawnPoints [SpawnIndex].position, SpawnPoints [SpawnIndex].rotation) as GameObject;
    }

    void Update(){
        if (lastBall.position.z > -0.904 ) {
            int SpawnIndex = Random.Range (0, SpawnPoints.Length);
            lastBall = Instantiate (ball, SpawnPoints [SpawnIndex].position, SpawnPoints [SpawnIndex].rotation) as GameObject;
        }
    }
} 
Ludovic Feltz
  • 11,416
  • 4
  • 47
  • 63
  • Thank you,but I am getting an error,it's saying "An explicit conversion exists (are you missing a cast?)" – alter ego Nov 03 '16 at 15:12
  • 1
    @alterego Replace `lastBall = Instantiate (ball, SpawnPoints [SpawnIndex].position, SpawnPoints [SpawnIndex].rotation);` **with** `lastBall = Instantiate (ball, SpawnPoints [SpawnIndex].position, SpawnPoints [SpawnIndex].rotation) as GameObject;` – Programmer Nov 03 '16 at 15:15
  • @alterego Does the edit suggested by programmer solve your issue? – Ludovic Feltz Nov 03 '16 at 15:23
  • Its just respawing too many object at a time after I hit play. – alter ego Nov 03 '16 at 16:28
  • On line 14, is it best practice/more efficient to do `as GameObject` like you are doing there or cast to GameObject with `(GameObject)` at the beginning of the line? That might fix @alterego 's problem of "An explicit conversion exists" – yummypasta Nov 04 '16 at 00:43
  • @yummypasta The only difference between the two are `as GameObject` will return `null` if the cast is impossible and casting with`(GameObject)` will throw an exception instead. See: [Casting vs using the 'as' keyword in the CLR](http://stackoverflow.com/questions/496096/casting-vs-using-the-as-keyword-in-the-clr) – Ludovic Feltz Nov 04 '16 at 09:36