I have a Spaceship and a Coin which is falling down. At the bottom of the screen the coin destroys itself (which I wanted to happen). You can of course move the spaceship. It has a 2d Collider (not trigger). The coin gets spawned randomly. The text which displays my coins works (i’ve tested it). So it must be my colliders I think which don’t work.
Cheers!
Here is my coin’s script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class CoinScript : MonoBehaviour {
public Camera cam;
public Rigidbody2D rb2D;
public GameObject bullet;
public bool spawn = true;
private float maxWidth;
private float RandRangeWait;
private float RandomWaitS = 10.0f;
private float RandomWaitE = 15.0f;
public Text coinText;
private float coin;
// Use this for initialization
void Start () {
rb2D = GetComponent<Rigidbody2D> ();
if (cam == null) {
cam = Camera.main;
}
Vector3 upperCorner = new Vector3 (Screen.width, Screen.height, 0.0f);
Vector3 targetWidth = cam.ScreenToWorldPoint (upperCorner);
maxWidth = targetWidth.x;
StartCoroutine (Spawn());
}
void Update(){
coinText.text = "Coins: " + coin.ToString ();
}
IEnumerator Spawn() {
yield return new WaitForSeconds (5.0f);
while (spawn==true) {
Vector3 spawnPosition = new Vector3 (Random.Range (-maxWidth, maxWidth), 10.0f , 0.0f);
Quaternion spawnRotation = Quaternion.identity;
Instantiate (bullet, spawnPosition, spawnRotation);
yield return new WaitForSeconds (Random.Range (RandomWaitS, RandomWaitE));
}
}
IEnumerator Wait() {
yield return new WaitForSeconds (10.0f);
}
void OnTriggerEnter2D (Collider2D other){
if (other.gameObject.tag == "ShipTag") {
coin = PlayerPrefs.GetFloat ("Coins");
coin = coin + 1;
PlayerPrefs.SetFloat ("Coins", coin);
Debug.Log ("COIN");
}
if (other.gameObject.tag == "Destroy"){
Destroy (gameObject);
}
}
}