Question by
goldenking95 · Mar 28, 2016 at 01:07 AM ·
destroyvariableupdatepublic
Can't update a public Variable in another script..
Hey guys, I'm stuck at something that in my opinion should work. But hey, would't life be too easy that way.
I want to update a variable when a character dies, and display this on screen. I currently have this in my EnemiesKilled script:
using UnityEngine;
using UnityEngine.UI;
public class EnemiesKilled : MonoBehaviour
{
public Text text;
public int KilledEnemies = 0;
// Use this for initialization
void Start()
{
text = text.GetComponent<Text>();
}
// Update is called once per frame
void Update()
{
text.text = "Killed: " + KilledEnemies;
if (KilledEnemies > 50)
{
Time.timeScale = 0f;
//insert enemy killed penalty
}
}
}
And I have this in my other script:
public class EnemyScript : MonoBehaviour
{
public int EnemyHealth = 10;
public EnemiesKilled enemiesKilled;
void DeductPoints(int DamageAmount)
{
EnemyHealth -= DamageAmount;
}
void Start()
{
enemiesKilled = enemiesKilled.GetComponent<EnemiesKilled>();
}
void Update()
{
if (EnemyHealth <= 0)
{
enemiesKilled.KilledEnemies++;
Destroy(gameObject);
}
}
}
Can anyone tell me what is wrong with my code. In advance thanks! Also other tips would be really helpfull! My enemies won't destroy anymore because of this part enemiesKilled.KilledEnemies++;
Comment
Best Answer
Answer by Addie · Mar 28, 2016 at 04:56 AM
@goldenking95 use FindObjectOfType to get the enemies killed script
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
public class EnemiesKilled : MonoBehaviour
{
public Text text;
public int killedEnemies;
void Start ()
{
text = GetComponent<Text>();
}
void Update ()
{
if(killedEnemies > 50)
{
Time.timeScale = 0f;
}
}
}
using UnityEngine;
using System.Collections;
public class EnemyScript : MonoBehaviour
{
public int enemyHealth = 10;
public EnemiesKilled enemiesKilled;
void Start ()
{
enemiesKilled = FindObjectOfType<EnemiesKilled>();
}
public void DeductHealth(int damage)
{
enemyHealth -= damage;
}
void Update ()
{
if(enemyHealth <= 0)
{
enemiesKilled.killedEnemies += 1;
Destroy(gameObject);
}
}
}