- Home /
How to make if the object == null then add gold?
Hi guys, okay my problem goes like this i have a damage script for the enemy in javascript then my add gold script is in C#, right now i wanted to make a C# script that able to state if the enemy is dead via gameObject == null then will Player.gold + 1. Is it possible guys? A script that will detect if the object is destroy or no longer there then auto add gold rather than when HP gone only add gold. The below script is not working, anyone have idea?
Enemy.cs public class enemy : MonoBehaviour {
public GameObject gameObject;
// Use this for initialization
void Start () {
gameObject = GameObject.FindWithTag("Player1");
}
// Update is called once per frame
void Update () {
if (gameObject == null){
Players.gold = Players.gold + 1;
Destroy (gameObject);
}
}
}
First thing I see is that you're using gameObject for your target. gameObject is a direct reference to Unity's gameObject internal functions and properties, directly affecting the object that the script is attached to. I believe that using it as a variable name will throw errors.
hmmm sir due to my limited knowledge i don't quite get you, if for my case how should i define it?
Just change the name of the variable to something other than 'gameObject.' Use 'target', or 'go', or 'player', or...
Also your logic will cause an error. I'm not sure, but I'm guessing you want != ins$$anonymous$$d of ==. The code as it stands will attempt to destroy a 'null' game object resulting in an error.
What he meant is you should give some other name for gameObject, like this GameObject target
You have written your if condition in update so it will keep on adding the gold.
Write somewhere else where the method tuns only once or take a bool variable and run it once
Furthermore, what he meant is you should give variable names that are relevant to what the script is doing. $$anonymous$$gestion by @robertbu sounds good if you want to add gold everytime Update()
is called. Otherwise, do suggestion by @united4life.
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
[I REALLY NEED HELP FAST]Help with enemy Shooting 1 Answer