So it’s probably something stupid but I can’t seem to figure it out…
I’m making a system where when you touch the “coin”, it gives +1 to the score and goes away, but I’m running into some issues. Here’s the main code with the text on it. (I know, it’s a lot more than just player movement on that script, but I’m just now learning how to make scripts talk to eachother…)
Here’s what’s on the player:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class PlayerMovement : MonoBehaviour
{
public float speed = 5.0f;
public float jumpHeight = 20.0f;
public float minX;
public float maxX;
public Text scoreText;
private int score;
private bool colorSwitch = true;
private bool isGrounded = false;
private Rigidbody2D myRigid;
void Start ()
{
myRigid = this.GetComponent<Rigidbody2D> ();
score = 0;
scoreText.text = "Coins: " + score.ToString();
}
void Update ()
{
if(Input.GetKeyDown (KeyCode.S))
{
colorSwitch = !colorSwitch;
}
if(colorSwitch)
{
this.GetComponent<SpriteRenderer> ().color = Color.black;
}
else
{
this.GetComponent<SpriteRenderer> ().color = Color.white;
}
}
void FixedUpdate ()
{
if (Input.GetKeyDown (KeyCode.Space) || Input.GetKeyDown (KeyCode.W) || Input.GetKeyDown (KeyCode.UpArrow))
{
if (isGrounded)
{
myRigid.velocity = new Vector2 (myRigid.velocity.x, jumpHeight);
Debug.Log (" I am jumping ");
}
}
if (Input.GetKey (KeyCode.A) || Input.GetKey (KeyCode.LeftArrow))
{
myRigid.velocity = new Vector2 (-speed, myRigid.velocity.y);
Debug.Log (" Moving RIGHT ");
}
if (Input.GetKey (KeyCode.D) || Input.GetKey (KeyCode.RightArrow))
{
myRigid.velocity = new Vector2 (speed, myRigid.velocity.y);
Debug.Log (" Moving LEFT ");
}
if (myRigid.position.x <= minX)
{
myRigid.position = new Vector2 (minX, myRigid.position.y);
}
else if (myRigid.position.x >= maxX)
{
myRigid.position = new Vector2 (maxX, myRigid.position.y);
}
}
void OnTriggerEnter2D ()
{
isGrounded = true;
Debug.Log (" Detecting ground ");
}
void OnTriggerExit2D ()
{
isGrounded = false;
Debug.Log (" Not touching ground ");
}
void OnCollisionEnter2D ()
{
if (myRigid.CompareTag ("Coin"))
{
setScore ();
}
}
void setScore ()
{
if (CoinDestroy.isCollected == false)
{
score = score + 1;
scoreText.text = "Coins: " + score.ToString ();
}
}
}
Here’s what’s on the coins:
using UnityEngine;
using System.Collections;
public class CoinDestroy : MonoBehaviour
{
static public bool isCollected = false;
static void OnCollisionEnter2D(Collision2D col)
{
if (col.gameObject.tag == "Player")
{
col.gameObject.SetActive (false);
isCollected = true;
}
}
}
Error message:
As you can see, the only way I’ve figured out how to do this is to set it invisible instead of destroying it.
Any tips? Is there an easier way to approach this? This seems like a lot for just a coin I can pick up. I’ve watched the tutorials and looked through their code and can’t figure out why mine isn’t working.
An explanation would be awesome as well… Thanks guys.