Question by
MarcelGar6 · Jun 16, 2016 at 04:17 AM ·
prefabvariablecollider2d
OnCollisionEnter2D not changing variable
Hey guys. I'm having issues with a 2D labyrinth game and probably it's extremely easy to solve but I couldn't figure it out by myself and it's the first time ever I ask here, so if I'm breaking any rules, I'm sorry.
Whenever I collide with an enemy, I need to subtract the integer from variable "lives" and add to "keys" when I collide with a key. I have hearts drawn on GUI and they are really disappearing when I touch an enemy, but the value of "lives" isn't changing in the inspector and the same happens with the value of "keys" and the number shown on screen is always 0. The player has a collider and Rigidbody, the enemies and keys are prefabs and only have colliders. If more details are needed, ask me. Thanks!
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class Movement : MonoBehaviour
{
Rigidbody2D rbody;
public float walkspeed = 4f;
Animator anim;
public GameObject Player;
public bool moveLeft = false;
public bool moveRight = false;
public bool moveUp = false;
public bool moveDown = false;
public int lives = 3;
public int keys = 0;
public float posX = 0;
public float posY = 0;
public Text keysText;
void Start()
{
rbody = GetComponent<Rigidbody2D>();
anim = GetComponent<Animator>();
anim.SetFloat("input_y", -1f);
}
void Update()
{
switch (lives)
{
case 2:
Destroy(GameObject.Find("heart_3"));
break;
case 1:
Destroy(GameObject.Find("heart_2"));
break;
case 0:
Destroy(GameObject.Find("heart_1"));
break;
default:
print("Deu merda!");
break;
}
Vector2 movement_vector = new Vector2(posX, posY);
if (movement_vector != Vector2.zero)
{
anim.SetBool("isWalking", true);
anim.SetFloat("input_x", movement_vector.x);
anim.SetFloat("input_y", movement_vector.y);
}
else
anim.SetBool("isWalking", false);
rbody.MovePosition(rbody.position + movement_vector * walkspeed * Time.deltaTime);
}
public void MoveUp()
{
posY = 1f;
}
public void MoveDown()
{
posY = -1;
}
public void MoveLeft()
{
posX = -1;
}
public void MoveRight()
{
posX = 1;
}
public void Stop()
{
posX = 0;
posY = 0;
}
void OnCollisionEnter2D(Collision2D colisor)
{
if (colisor.gameObject.tag == "vertical" || colisor.gameObject.tag == "horizontal")
{
gameObject.transform.position = new Vector3(-6.67f, 2.63f, 0f);
lives -= 1;
}
if (colisor.gameObject.tag == "keys")
{
gameObject.transform.position = new Vector3(-6.67f, 2.63f, 0f);
keys += 1;
}
}
void OnGUI()
{
keysText.text = "Chaves: " + keys.ToString();
}
}
Comment