Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by Luucccc · Jan 22, 2018 at 09:25 PM · c#variable

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;
     }
 }


Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

2 Replies

· Add your reply
  • Sort: 
avatar image
0
Best Answer

Answer by KittenSnipes · Jan 23, 2018 at 08:55 AM

@Luucccc

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;
     }
Comment
Add comment · Show 1 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image Luucccc · Mar 20, 2018 at 02:50 PM 0
Share

Thankyou very much, really helpful solution. I wasn't thinking straight

avatar image
0

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.

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

433 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

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

Is it possible to use a variable as a Type? 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges