- Home /
Unity Error: Only assignment, call, increment, decrement, and new object expressions can be used as a statement
This script (ShortRange tower bullet) acquires the monster component of another script (MonsterScript) and takes its health by the amount of damage this bullet does. The bullet is a public float.
The second line of the else method is getting an error (health - damage;)
void OnTriggerEnter(Collider co) {
if (co.gameObject.tag == "Monster") {
if (co.gameObject.GetComponent<MonsterScript> ().health <= 0) {
co.gameObject.GetComponent<MonsterScript> ().Death();
Destroy (co.gameObject);
}else{
co.gameObject.GetComponent<MonsterScript> ().myHealthBar.text = co.gameObject.GetComponent<MonsterScript> ().myHealthBar.text.Remove(co.gameObject.GetComponent<MonsterScript> ().myHealthBar.text.Length - 1 );
co.gameObject.GetComponent<MonsterScript> ().health - damage;
}
Here's the whole script
public class ShortRangeTowerBullet : MonoBehaviour {
// Speed
public float speed = 10;
// Target (set by Tower)
public Transform target;
//Damages the monster
public float damage;
void FixedUpdate() {
// Still has a Target?
if (target) {
// Fly towards the target
Vector3 dir = target.position - transform.position;
rigidbody.velocity = dir.normalized * speed;
} else {
// Otherwise destroy self
Destroy(gameObject);
}
}
void OnTriggerEnter(Collider co) {
if (co.gameObject.tag == "Monster") {
if (co.gameObject.GetComponent<MonsterScript> ().health <= 0) {
co.gameObject.GetComponent<MonsterScript> ().Death();
Destroy (co.gameObject);
}else{
co.gameObject.GetComponent<MonsterScript> ().myHealthBar.text = co.gameObject.GetComponent<MonsterScript> ().myHealthBar.text.Remove(co.gameObject.GetComponent<MonsterScript> ().myHealthBar.text.Length - 1 );
co.gameObject.GetComponent<MonsterScript> ().health - damage;
}
}
}
}
Answer by cjdev · Aug 20, 2015 at 04:13 AM
You are subtracting damage from health but not assigning it to anything. Try using the -=
operator to assign health to health - damage:
co.gameObject.GetComponent<MonsterScript> ().health -= damage;
It says a different error where it "Cannot implicitly convert type "float" to "int". I'm trying to make a public variable where i can just simply adjust the bullet damage depending on the tower.
Is there another way in doing it?
Thank you by the way
If your health variable in $$anonymous$$onsterScript is an int then you might want to change the types to match. You could also cast the float to an int to convert it explicitly like health -= (int)damage;
yep it definitely works, thank you. Still somewhat a beginner in c# scripting
Your answer
Follow this Question
Related Questions
Expecting ) found = 1 Answer
"Health" value doesn't change? 1 Answer
How to make your player health subtract when enemies come into contact with you 3 Answers
Animation + Attack when in range 1 Answer
Health Bar fire damage 1 Answer