- Home /
Trying to get this coin system to work to no avail
Hi, I'm trying to get these two scripts working but neither seem to working the way I want them to. I'm trying to destroy an object upon collision, make a sound effect play, and then add one to my score.
Here's my code, any help would be appreciated:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ScoreScript : MonoBehaviour {
public static int scoreValue = 0;
Text score;
// Use this for initialization
void Start () {
score = GetComponent<Text> ();
}
// Update is called once per frame
void Update () {
//score.text = "Score: " + scoreValue;
}
}
using UnityEngine;
using System.Collections;
public class ObjectDestroy : MonoBehaviour {
public AudioClip coinSound;
AudioSource audioSource;
void Start()
{
audioSource = GetComponent<AudioSource>();
}
IEnumerator OnTriggerEnter (Collider other){
if(other.tag == "Player")
{
ScoreScript.scoreValue += 1;
audioSource.PlayOneShot (coinSound);
yield return 0.2f;
Destroy(gameObject);
}
}
}
Answer by pako · Feb 23, 2019 at 11:10 AM
You don't say what exactly happens when you run the code you posted, which might be helpful. Anyway, I haven't tested this, but maybe you want to try the following changes:
void OnTriggerEnter (Collider other){
if(other.tag == "Player")
{
ScoreScript.scoreValue += 1;
StartCoroutine(DestroyPlayer());
}
}
IEnumerator DestroyPlayer(){
audioSource.PlayOneShot (coinSound);
yield return 0.2f;
Destroy(gameObject);
}
Glad it worked!
Apparently, OnTriggerEnter
cannot be used as a coroutine. Currently the documentation on which Unity callbacks can be coroutines is incomplete, so I'd be very careful about such usage.
@hankcheesecake I'd really appreciate if you accepted my answer by clicking on the checkmark (just below the up/down vote on the left side of the answer). We'll both get reputation points if you do :-)
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
how to keep track of bricks broken 1 Answer
Basic collision not working - c# 1 Answer
Coin pickup script not working..? 1 Answer