I’m trying to get the following script working, I think I miss something simple but I don’t see what.
It’s about spawning an object after every 10 score points.
Scoremanager.instance.GetScore() returns an int with the score.
CoinManager:
using UnityEngine;
using System.Collections;
public class CoinFlightManager : MonoBehaviour {
public GameObject coinFlightPrefab;
private int oldScore;
//If you ever need the coin to stop spawning, by doing: CoinFlightManager.spawnCoin = false;
public static bool spawnCoin = true;
void Start () {
}
public void SpawnCoin ()
{
if (spawnCoin == true) {
if (ScoreManager.instance.GetScore () == oldScore + 10) {
Instantiate (coinFlightPrefab);
oldScore = ScoreManager.instance.GetScore ();
}
}
}
}
CoinScript (on the coin itself):
using UnityEngine;
using System.Collections;
public class CoinScript : MonoBehaviour {
//Set these variables to whatever you want the slowest and fastest speed for the coins to be, through the inspector.
//If you don't want coins to have randomized speed, just set both of these to the same number.
//For Example, I have these set to 2 and 5
public float minSpeed;
public float maxSpeed;
//Set these variables to the lowest and highest y values you want coins to spawn at.
//For Example, I have these set to 1 and 4
public float minY;
public float maxY;
//Set this variable to how far off screen you want the coins to spawn, and how far off the screen you want the coins to be for it to despawn. You probably want this value to be greater than or equal to half the width of your coins.
//For Example, I have this set to 4, which should be more than enough for any coins.
public float buffer;
float speed;
float camWidth;
void Start() {
//Set camWidth. Will be used later to check whether or not coin is off screen.
camWidth = Camera.main.orthographicSize * Camera.main.aspect;
//Set Coin Movement Speed, and Position to random values within range defined above
speed = Random.Range(minSpeed, maxSpeed);
transform.position = new Vector3(-camWidth - buffer, Random.Range(minY, maxY), transform.position.z);
}
// Update is called once per frame
void Update() {
//Translates the cloud to the right at the speed that is selected
transform.Translate(speed * Time.deltaTime, 0, 0);
//If cloud is off Screen, Destroy it.
if(transform.position.x - buffer > camWidth) {
Destroy(gameObject);
}
}
}