i am making a 2d platform game in the game there is a player a key and chest
i have labelled the key with the tag “chestKey”
i have a script on the chest called “ChestKey”
and a script on the player called player interaction.
in the chestKey script i have a public bool called GotKey
i want to change that bool to true from the player interaction script using ontriggerenter2d
public class ChestKey : MonoBehaviour {
public LevelManager LevelManager;
public int chestPoints = 250;
public bool GotKey ;
// Use this for initialization
void Start ()
{
GameObject.FindGameObjectsWithTag("Player");
GameObject.FindGameObjectsWithTag("chestKey");
GotKey = false;
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == "Player" && GotKey)
{
Debug.Log("congratulations chest is open", gameObject);
LevelManager.AddPoints(chestPoints);
}
if (other.tag == "Player" && !GotKey)
{
Debug.Log("You Need the Key", gameObject);
}
}
}
player interaction Script
using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;
public class PlayerInteraction : MonoBehaviour
{
public LevelManager LevelManager;
public HealthBar HealthBar;
public int cogPoints = 10;
public int gemPoints = 52;
public GameObject Chest;
public ChestKey chestKey;
public Rigidbody2D rb;
//reference to healthbar script so this script can find it
void Start()
{
GameObject.FindGameObjectsWithTag("HealthBar");
rb = GetComponent<Rigidbody2D>();
chestKey = GameObject.Find("Chest").GetComponent<ChestKey>();
}
void OnTriggerEnter2D(Collider2D other)
{
Vector2 dir = transform.position - other.transform.position;
dir.Normalize();
if (other.tag == "chestKey")
{
Debug.Log("you have the key", gameObject);
// Chest.GetComponent<>;
}
//add cog points to score
if (other.tag == "Cog")
{
LevelManager.AddPoints(cogPoints);
}
//add gem points to score
if (other.tag == "Gem")
{
LevelManager.AddPoints(gemPoints);
}
//Health pick up add 40 to health
if (other.tag == "Health")
{
HealthBar.curHealth += 40;
}
// NME takes health of player
if (other.tag == "NME")
{
HealthBar.curHealth -= 10;
//makes player bounce if hit by enemy
Rigidbody2D rbOther = this.gameObject.GetComponent<Rigidbody2D>();
rbOther.AddForce(dir * 1500 );// *Time.deltaTime);
// Debug.Log(rbOther);
}
// if current health = 0 load gameover screen
if (HealthBar.curHealth == 0)
{
SceneManager.LoadScene(1);
}
}
}
i cant seem to get the reference right can anyone help?