- Home /
MY variables RESET When calling Destroy() In Unity
I need to Collect and Destroy the money But When i add Destroy or equal function it resets and always says 5 instead of 5-10-15... I Watched videos on Youtube And only difference we making is they are like Class object; me Class object = new Class(); but i dont think this can cause the problem because when i remove destroy() function problem solved ! but i cant :( can you help this poor developer ? using System.Collections; using System.Collections.Generic; using UnityEngine;
public class moneysystem : MonoBehaviour {
bool intrigger;
variables asd = new variables();
private void OnTriggerEnter(Collider other)
{
intrigger = true;
}
private void OnTriggerExit(Collider other)
{
intrigger = false;
}
public void FixedUpdate()
{
if (intrigger)
{
if (Input.GetKeyDown(KeyCode.G))
{
asd.summoney = asd.money += asd.moneyonpaper;
Debug.Log(asd.summoney);
asd.summoney = asd.lastmoney;
Debug.Log(asd.lastmoney);
Destroy(this.gameObject); // when I remove This then there is no problem remains
// I also tried Destroy(gaemobject) and gameobject.setactive(false) and same problem
Debug.Log(asd.lastmoney);
}
Variables.cs using System.Collections; using System.Collections.Generic; using UnityEngine;
public class variables : MonoBehaviour {
public int moneyonpaper = 5;
public int money;
public int summoney;
public int lastmoney;
}
Answer by unidad2pete · Aug 14, 2017 at 09:53 AM
You need 2 scripts.
1- Create new c# script named Variables
2- Add this code to Variables script and save.
public class Variables : MonoBehaviour
{
public int moneyonpaper = 5;
public int money;
public int summoney;
public int lastmoney;
}
3- Make new empty GameObject to scene, rename to Variables
4- Add Variables script to Variables GameObject
5- Modify your actual script
public class moneysystem : MonoBehaviour
{
bool intrigger;
public Variables asd;
private void Start()
{
asd = GameObject.Find("Variables").GetComponent<Variables>();
}
private void OnTriggerEnter(Collider other)
{
intrigger = true;
}
private void OnTriggerExit(Collider other)
{
intrigger = false;
}
public void FixedUpdate()
{
if (intrigger)
{
if (Input.GetKeyDown(KeyCode.G))
{
if (asd != null)
{
asd.money += asd.moneyonpaper;
Debug.Log(asd.money);
Destroy(gameObject);
}
}
}
}
}
hank you so much can you tell me what was the missing part or what was the part i did wrong pls ?
Your answer
Follow this Question
Related Questions
Cronómetro 1 Answer
"on" and "off" the effect. 0 Answers
A* pathfinding generating new path when created new obstacle 0 Answers
Help with rotation. 1 Answer
Can I use GetComponents reference outside Of awake and start functions 1 Answer