- Home /
Editing a value attached to a gameobject without changing others with the same script,Editing a variable that's attached to a gameobject, without changing others with the same script
Hello, I'm trying to generate cubes with random health, which when clicked the health value of the cubed clicked will decrease by 1, until 0, then it will be destroyed. And I'm trying to use a script on the camera to "take away health" from a variable attached to each gameobject and the value i edit doesn't seem to change.
tl;dr I've got a script attached to the camera to "take health away from the specific cube clicked", but when I grab the health value from the gameobject I can't seem to edit the value.
Camera Script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
using UnityEngine;
public class Hitdetect : MonoBehaviour {
public Text scoreText;
private int score;
void Update () {
//Updates score board
scoreText.text = score.ToString();
//If number of touches on screen is 1
if (Input.touchCount == 1) {
Touch touch = Input.GetTouch (0);
Ray ray = Camera.main.ScreenPointToRay(touch.position);
RaycastHit hit;
//If ray hits object 100 units away
if (Physics.Raycast(ray, out hit,100)) {
//If hit object is called "Block"
if (hit.collider.gameObject.name == "Block") {
//Grabs objects script
Generator GeneratorScript = hit.collider.gameObject.GetComponent<Generator>();
//Decreasing health
GeneratorScript.health -= 1;
//If health is below 0
if (GeneratorScript.health <= 0) {
Destroy(hit.collider.gameObject);
score=score+1;
}
}
}
}
}
}
Generator Script:
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
public class Generator : MonoBehaviour {
//MESH AND MATERIAL VARIABLES
public Mesh mesh;
public Material material;
//MAIN LOOP VARIABLES
public int numObjects;
//Temp stores random position
private Vector3 randomPosition;
//Defines range of generator plane
public int generateSize;
//temp storage of usedpositions
private Vector3[] usedPosition = new Vector3[20];
//main counter
private int mainCount;
public int health;
public int maxHealth;
private void Start () {
mainCount=0;
//For number of objects created less than numobjects
for (;mainCount<numObjects;) {
//Stores a random vector3 position in defined range
randomPosition = new Vector3(Random.Range(generateSize,-generateSize),0,Random.Range(generateSize,-generateSize));
//if random position hasnt been used during this loop
if (!usedPosition.Contains(randomPosition)) {
//randomised health value 1-4 currently
health = Random.Range(1,maxHealth);
//Create gameobject cube assigning it health, mesh, material
new GameObject("Block").AddComponent<Generator>().Initialize(mesh,material,randomPosition,health);
//Add position to usedposition array
usedPosition[mainCount]=randomPosition;
mainCount=mainCount+1;
}
}
}
//When no objects left in scene restart
private void Update() {
if(GameObject.Find("Block")== null) {
Start();
}
}
private void Initialize (Mesh mesh_in, Material material_in, Vector3 randomPosition_in, int health_in) {
//Rendering objects
gameObject.AddComponent<BoxCollider>();
gameObject.AddComponent<MeshFilter>().mesh = mesh_in;
gameObject.AddComponent<MeshRenderer>().material = material_in;
gameObject.GetComponent<Generator>().health = health_in;
//Moves object to random generated position
transform.position = randomPosition_in;
}
}
Answer by KittenSnipes · Jan 23, 2018 at 08:55 AM
I recommend making a separate class for health. I think it should look like this:
//The maxHealth of the player.
public float maxHealth = 1000;
//Amount of damage done to player using the hurt key.
public float hurtAmount = 100;
//Key in which when clicked hurts the player.
public KeyCode HurtKey = KeyCode.Q;
//HealthSlider on a canvas to mark how much health the player has.
public UnityEngine.UI.Slider healthSlider;
//The currentHealth reference of the player.
float currentHealth;
void Start()
{
//Set currentHealth to maxHealth.
currentHealth = Random.Range(1, maxHealth);
//Sets the slider to have the maxHealth.
healthSlider.maxValue = maxHealth;
//Then sets its value to currentHealth.
healthSlider.value = currentHealth;
}
void Update()
{
//If the hurt key is pressed.
if (Input.GetKeyDown(HurtKey))
{
//Then damage the player for the hurt amount.
TakeDamage(hurtAmount);
}
}
void TakeDamage(float DamageAmount)
{
//If our currentHealth less than or equal to 0.
if (currentHealth <= 0)
{
//Then set currentHealth equal to 0.
currentHealth = 0;
//Then return so nothing else happens from here.
return;
}
//Damage our player by the regular damage amount.
currentHealth -= DamageAmount;
//Set our slider to show our current health.
healthSlider.value = currentHealth;
}
Thankyou very much, really helpful solution. I wasn't thinking straight
Answer by corpsinheretoo · Jan 24, 2018 at 12:45 PM
public int health;
Because health is public, if you have ever set the value in the editor, that value will override any change you attempt in code. If this is the case, change the exposure to private; then either leave it private or you can make it public again but do not set it via the editor.
Your answer

Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Calling a variable in C#? 1 Answer
Variable is always false... 1 Answer